<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/10/9
 * Time: 下午5:32
 */
class Orders extends Eloquent
{
	protected $primaryKey = 'order_id';
    protected $table = "orders";
    //能够取消的订单的状态
    public static $chanage=array(1111,1411,1112,1412,1312);
    public static $cancancel_status=array(1011,1111,1112,1112,1411,1412,1312);
    public static $add_product=array(1111,1411,1412,1112,1215,1216,1312);
    public static $change_price=array(1111,1411,1412,1112,1215,1216,1312,1420);
    public static $delete_product=array(1111,1411,1412,1112,1215,1216,1312);
   	public static $orderStart=array(1411,1112,1412,1312);
   	public static $in_park=array(1211,1411,1112,1212,1412,1215,1216,1217,1312);
   	public static $serviceStart=array(1215,1216);
   	//根据车型和车牌号获取特定状态订单
   	public static $search_orders=array(1412,1112,1212,1215,1312);
    //能够门店展示的 订单状态
    public static $search_order=array(1018,1112,1213,1214,1215,1216,1217,1219,1317,1411,1412,1416,1417,1419,1420,1117,1312);
   	//可终止订单的状态
   	public static $stop_order=array(1215,1216);
   	//订单结算完成
   	public static $complete=array(1017,1117,1217,1317,1417,1018);
    //可以开发票的 状态
    public static $invoice=array(1417,1419,1018);
    public static $end_status=array(1216,1217,1417,1416,1018,1219,1419,1420);
    public static $prer_status=array(1216,1217,1417,1416,1018,1420);

    public static $confirm=array(1112,1412,1213,1214,1215,1216,1416,1312,1420);  //订单已确认
    public static $to_be_confirmed=array(1011,1111,1411);  //待确认
    public static $to_be_eval=array(1117,1217,1317,1417);//待评价订单
    public static $cancel_and_end=array(1010,1110,1210,1310,1410,1219,1419);//已取消 and 已终止
    public static $order_source = array(10,11,14); //微站 cms 门店端
    public static $update_engineer = array(1215,1216,1420); //修改技师

    public static $place = array(
        '1' => '上门保养',
        '2' => '到店保养',
    );
    public static $service_type = array(
        '1' => '保养',
        '2' => '维修',
        '3' => '美容',
        '4' => '保险',
    );

    public static $status = array(
        "1010"=>"已取消",
        "1011"=>"已预约",//用户生成订单
        "1017"=>"已完成",//复检完成，
        "1018"=>"已完成",//用户评价订单完成，

        "1111"=>"待确认",
        "1110"=>"已取消",//用户评价订单完成，
        "1112"=>"已确认",//用户下完单客服确认完毕
        "1117"=>"已完成",//用户下完单客服确认完毕

        "1210"=>"已取消",//技师取消订单
        "1211"=>"待确认",//技师代用户下单
        "1212"=>"已确认",//技师代用户下单
        "1213"=>"已确认",//技师上门车 出发
        "1214"=>"已确认",//技师上门车 到达
        "1215"=>"已确认",//车辆开始服务
        "1216"=>"已确认",//车辆结束服务
        "1217"=>"已完成",//复检完成
        "1219"=>"已终止",

        "1310"=>"已取消",
        "1312"=>"已确认",//当天门店订单默认系统已确认
        "1317"=>"已完成",//复检完成

        "1410"=>"已取消",
        "1411"=>"待确认",
        "1412"=>"已确认",
        "1416"=>"已确认",
        "1417"=>"已完成",
        "1419"=>"已终止",
        "1420"=>"已确认",
    );
    //套餐卡status
    public static $service_card_status = array(
        "1010"=>"已取消",
        "1011"=>"待支付",
        "1310"=>"已取消",
        "1410"=>"已取消",
        "1411"=>"待支付",
        "1417"=>"已完成",
    );

    public static $order_status = array(
        "2" => array(1011,1111,1411),//待确认
        "3" => array(1112,1312,1412,1213,1214,1215,1216,1416,1420),//已确认
        "4" => array(1117,1217,1317,1417), //待评价
        "5" => array(1018),//已评价
        "6" => array(1010,1110,1210,1310,1410), //已取消
        "7" => array(1219,1419),//已终止
    );

    //C端 api3.0订单状态配置
    public static $order_status_wechat3 = array(
        "2" => array(1011,1111,1411),//待确认
        "3" => array(1112,1312,1412,1213,1214),//已确认--待服务
        "4" => array(1215,1216,1416,1420),//已确认--服务中
        "5" => array(1117,1217,1317,1417), //已完成--待评价
        "6" => array(1018),//已完成--已评价
        "7" => array(1010,1110,1210,1310,1410), //已取消
        "8" => array(1219,1419),//已终止
    );
    //订单列表不显示的支付用户
    public static $not_show_pay_user = array(1000003321,1000003311,1000003305);
    public function maintenanceShops(){
        return $this->hasOne('MaintenanceShops','id','shop_id');
    }
    public static $paytype=array(
        "0"=>"未支付",
        "1"=>"线下支付现金",
        "2"=>"支付宝",
        "3"=>"微信",
        "4"=>"大众点评",
        "5"=>"其他",
        "6"=>"线下支付挂单",
        "7"=>"刷卡",
        "8"=>"余额支付",
        "9"=>"复合结算",
        "10"=>"不记账结算",
        "11"=>"线下支票",
        "12"=>"划拨",
        "13"=>"保险",
        "14"=>"调整充值",
        "15"=>"银行汇款",
        "16"=>"百度钱包",
        "17"=>"易付宝",
        "18"=>"京东钱包",
        "19"=>"QQ钱包",
        "20"=>"智能pos",
        '49'=>'洗车卡支付',
        '50'=>'线上洗车卡支付',
        '69'=>'免费支付',
    );

    //门店工位统计订单状态
    public static $staion=array(
        1117,
        1217,
        1317,
        1417,
        1018,
        1219,
        1419
    );

    //C端车辆状态--服务中车辆状态
    public static $car_service_status=array(
        //1011, 1111, 1411, 1112, 1312, 1412, 1213, 1214, 1215, 1216, 1416, 1420
        1215, 1216, 1416, 1420
    );

    //C端车辆状态--服务中车辆状态
    public static $car_in_store_status=array(
        1117, 1217, 1317, 1417, 1018
    );

    //C端车辆状态--取消/终止的订单车辆
    public static $car_cancel_status=array(
        1010, 1110, 1210, 1310, 1410, 1219, 1419
    );



    /**
   	 * @Author:      zwh
   	 * @DateTime:    2016-1-27 13:35:48
   	 * @Description: 添加出库单方法
   	 */
    /**
     * @Author:      lyt
     * @DateTime:  2017-08-01 14:49:03
     * @Description: 废弃 代码 测试关闭  
     */
   	// public static function saveMaintenanceOutOrder($data,$product_type,$order_id,$shop_id){
   	//     return DB::transaction(function () use ($data,$product_type,$order_id,$shop_id) {
   	//         if($product_type =='promotion'){
    //    	        foreach($data as $d){
    //    	            if(sizeof($d['item'])>0){
    //        	            foreach($d['item'] as $item){
    //        	                $mop=new MaintenanceOutOrder();
    //        	                $mop->shop_id=$shop_id;
    //        	                $mop->status=0;
    //        	                $mop->type=0;
    //        	                $mop->product_type=$product_type;
    //        	                $mop->item_id=$item['item_id'];
    //        	                $mop->product_item_id=$item['id'];
    //        	                $mop->number=$item['num'];
    //        	                $mop->order_id=$order_id;
    //        	                $mop->save();
    //        	            }
    //    	            }
    //    	        }
   	//         }else if($product_type =='base'){
   	//             if(sizeof($data)>0){
   	//                 foreach($data as $item){
   	//                     $mop=new MaintenanceOutOrder();
   	//                     $mop->shop_id=$shop_id;
   	//                     $mop->status=0;
   	//                     $mop->type=$item['item_type'];
   	//                     $mop->product_type=$product_type;
   	//                     $mop->item_id=$item['item_id'];
   	//                     $mop->product_item_id=$item['id'];
   	//                     $mop->number=$item['num'];
   	//                     $mop->order_id=$order_id;
   	//                     $mop->save();
   	//                 }
   	//             }
   	//         }else if($product_type =='non_standard'){
   	//             if(sizeof($data)>0){
   	//                 foreach($data as $item){
    //                     $mop=new MaintenanceOutOrder();
    //                     $mop->shop_id=$shop_id;
    //                     $mop->status=0;
    //                     $mop->type=$item['type'];
    //                     $mop->product_type=$product_type;
    //                     $mop->item_id=$item['item_id'];
    //                     $mop->product_item_id=$item['id'];
    //                     $mop->number=$item['num'];
    //                     $mop->order_id=$order_id;
    //                     $mop->save();
   	//                 }
   	//             }
   	//         }
   	//     });
   	// }

   	/**
   	 * @Author:      zwh
   	 * @DateTime:    2016-1-27 13:35:48
   	 * @Description: 检查是否已出过库
   	 */
    /**
     * @Author:      lyt
     * @DateTime:  2017-08-01 14:43:46
     * @Description: 测试 废弃 该方法 已经不用该方法 
     */
   	// public static function isOutOrders($order_id,$order_product_id){
   	//     $order_product=OrderProduct::find($order_product_id);
   	//     $product_type=$order_product->product_type;
    //     if($product_type =='promotion'){
    //         $opp=OrderProduct::getOrderPromotionProductPackage($order_id,$order_product_id);
    //         foreach($opp as $_opp){
    //             if(sizeof($_opp['item'])>0){
    //                 foreach($_opp['item'] as $item){
    //                     $moo=MaintenanceOutOrder::where('order_id',$order_id)->where('item_id',$item['item_id'])->where('product_item_id',$item['id'])->whereIn('status',array(0,1,2))->first();
    //                     if($moo){
    //                         return true;
    //                     }
    //                 }
    //             }
    //         }
    //     }else if($product_type =='base'){
    //         $opi=OrderProduct::getOrderProductItemBase($order_id,$order_product_id);
    //         if(sizeof($opi)>0){
    //             foreach($opi as $item){
    //                 $moo=MaintenanceOutOrder::where('order_id',$order_id)->where('item_id',$item['item_id'])->where('product_item_id',$item['id'])->whereIn('status',array(0,1,2))->first();
    //                 $mop=new MaintenanceOutOrder();
    //                 if($moo){
    //                     return true;
    //                 }
    //             }
    //         }
    //     }else if($product_type =='non_standard'){
    //         $opns=OrderProduct::getOrderProductNonStandard($order_id,$order_product_id);
    //         if(sizeof($opns)>0){
    //             foreach($opns as $item){
    //                 //$op=OrderProduct::find($order_product_id);
    //                 $moo=MaintenanceOutOrder::where('order_id',$order_id)->where('item_id',$item['item_id'])->where('product_item_id',$item['id'])->whereIn('status',array(0,1,2))->first();
    //                 if($moo){
    //                     return true;
    //                 }
    //             }
    //         }
    //     }else if($product_type =='base'){
    //         $opi=OrderProduct::getOrderProductItemBase($order_id,$order_product_id);
    //         if(sizeof($opi)>0){
    //             foreach($opi as $item){
    //                 $moo=MaintenanceOutOrder::where('order_id',$order_id)->where('item_id',$item['item_id'])->where('product_item_id',$item['id'])->whereIn('status',array(0,1,2))->first();
    //                 $mop=new MaintenanceOutOrder();
    //                 if($moo){
    //                     return true;
    //                 }
    //             }
    //         }
    //     }
    //     return false;
   	// }
   	/**
   	 * @Author:      zwh
   	 * @DateTime:    2016-1-27 13:35:48
   	 * @Description: 检查是否已出过库(单品)
   	 */
   	public static function isOutOrder($order_id,$order_product_item_id,$product_type){
   	    if($product_type =='promotion'){
   	        $opi=OrderProductItem::find($order_product_item_id);
   	        if($opi){
                $moo=MaintenanceOutOrder::where('product_type','promotion')->where('product_item_id',$order_product_item_id)->whereIn('status',array(0,1,2))->first();
                if($moo){
                    return true;
                }
   	        }
   	    }else if($product_type =='enterprise'){
            $opei=OrderProductEsItem::find($order_product_item_id);
            if($opei){
                $moo=MaintenanceOutOrder::where('product_type','enterprise')->where('product_item_id',$order_product_item_id)->whereIn('status',array(0,1,2))->first();
                if($moo){
                    return true;
                }
            }
        }else if($product_type =='activity'){
            $opaci=OrderProductAcItem::find($order_product_item_id);
            if($opaci){
                $moo=MaintenanceOutOrder::where('product_type','activity')->where('product_item_id',$order_product_item_id)->whereIn('status',array(0,1,2))->first();
                if($moo){
                    return true;
                }
            }
   	    }else if($product_type =='base'){
   	        $opbi=OrderProductBaseItem::find($order_product_item_id);
   	        if($opbi){
                $moo=MaintenanceOutOrder::where('product_type','base')->where('product_item_id',$order_product_item_id)->whereIn('status',array(0,1,2))->first();
                if($moo){
                    return true;
                }
   	        }
   	    }else if($product_type =='non_standard'){
   	        $opns=OrderProductNonStandard::where('id',$order_product_item_id)->where('status',1)->first();
   	        if($opns){
       	        // $op=OrderProduct::find($opns->order_product_id);
                $moo=MaintenanceOutOrder::where('product_type','non_standard')->where('product_item_id',$order_product_item_id)->whereIn('status',array(0,1,2))->first();
                if($moo){
                    return true;
                }
   	        }
   	    }else if($product_type =='service_card'){
            $opns=OrderProductScItem::find($order_product_item_id);
            if($opns){
                // $op=OrderProduct::find($opns->order_product_id);
                $moo=MaintenanceOutOrder::where('product_type','service_card')->where('product_item_id',$order_product_item_id)->whereIn('status',array(0,1,2))->first();
                if($moo){
                    return true;
                }
            }
        }
   	    return false;
   	}


    /**
     * @Author:      lyt
     * @DateTime:    2016-04-14 09:43:56
     * @Description: 检查订单是否有出库 退库记录
     */

    public static function isOutReturnOrders($order_id){
      $moo=MaintenanceOutOrder::where('order_id',$order_id)->whereIn('status',array(0,1))->first();
      if($moo){
        return true;
      }
      $mro=MaintenanceReturnOrder::where('order_id',$order_id)->whereIn('status',array(0))->first();
      if($mro){
        return true;
      }
      return false;
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-05-24 14:29:16
     * @Description: 用于订单支付的接口
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 15:50:31
     * @Description: 接口废弃
     */
    public static function pay($order_id,$pay_array,$sc_user_id,$create_type,$order_status){
      return DB::transaction(function () use ($order_id,$pay_array,$sc_user_id,$create_type,$order_status) {
          $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();
         if(in_array($order->status,array(1117,1217,1417))){//是否已结算
              DB::rollback();
              $response = Lang::get("scs_error.order_status_error_40040");
              return $response;
          }
          // $user = Users::where('id',$order->user_id)->where('status',1)->first();
          $user = Users::find($order->user_id);
          $account = UserAccount::where('user_id',$order->user_id)->first();
          $temp_amount=0;
          foreach ($pay_array as $_pa) {
            // $tran_no = date('Ymd',time()).Common::generateCode();
            $tran_no = date('YmdHis',time()).Common::generateCode(8);
            $temp_amount+=$_pa["amount"]*100;
            $order_amount=$_pa["amount"]*100;
            $pay_type=$_pa["pay_type"];
            //各种进行判断
            if($user->type == 1 && $pay_type== 6){//如果是个人用户不能用挂账
                DB::rollback();
                $response = Lang::get("scs_error.order_user_notpay_40038");
                return $response;
            }
            if($order->user_id == 1000000000 && $pay_type == 8){
                DB::rollback();
                $response = Lang::get("scs_error.order_user_notpay_40059");
                return $response;
            }
            $o_p=new OrderPay;
            $o_p->order_id=$order_id;
            $o_p->pay_type=$pay_type;
            $o_p->amount=$order_amount;
            $o_p->status=1;
            $o_p->create_by=$sc_user_id;
            $o_p->tran_no=$tran_no;
            $o_p->create_type=$create_type;
            $o_p->save();

            if($pay_type== 1||$pay_type== 7){//现金 或者银行卡支付
                //记录用户充值
                // Account::record($order->user_id,$tran_no,1,'01',$order_amount,'订单结算充值');
                // //记录用户支出
                // Account::record($order->user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
                // //记录公司账户收入
                // Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');

                //记录用户充值 不记录充值记录  只记录流水
                Account::record($order->user_id,$order->shop_id,1,$tran_no,1,102,$order_amount,'订单结算充值,订单号:'.$order->order_id);
                //记录用户支出
                Account::record($order->user_id,$order->shop_id,1,$tran_no,2,202,$order_amount,'订单结算支出,订单号:'.$order->order_id);
                //记录公司账户收入
                Account::record_base('1',$tran_no,1,102,$order_amount,'订单结算收入,订单号:'.$order->order_id);

                //记录订单账务关系
                OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
            }
            if($pay_type == 8){//个人余额 暂时不判断 因为个人 余额现在都为空 新版本判断用户余额
              //记录用户支出

              // Account::record($order->user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
              // //记录公司账户收入
              // Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');
              // //记录订单账务关系
              // OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));


              $uad_balance=UserAccountDeatails::where("user_id",$user->id)->whereIn("acount_type",array(1,2))->sum("balance");   
              if(($uad_balance) >= $order_amount){
                  $arr=AcountUserRecharge::getUseRecharge($order->shop_id,$order->user_id,$order_amount,2,"asc");
                  if(sizeof($arr)>0){
                    foreach ($arr as $_arr) {
                      //记录了用户的充值消费记录
                      $aurs=new AcountUserRechargeSpend;
                      $aurs->aurr_id=$_arr->id;
                      $aurs->user_id=$order->user_id;
                      $aurs->buss_id=$o_p->id;
                      $aurs->type=1;
                      $aurs->amount=$_arr->user_amount;
                      $aurs->status=1;
                      $aurs->tran_no=$tran_no;
                      $aurs->shop_id=$order->shop_id;
                      $aurs->implement_time=date("Y-m-d H:i:s",time());
                      $aurs->save();
                      //更改充值记录消费的记录
                      AcountUserRecharge::where('id',$_arr->id)->update(array('current_amount'=> $_arr->current_amount -$_arr->user_amount,));
                      //记录个人 各种账户余额
                      Account::record($order->user_id,$_arr->shop_id,$_arr->acount_type,$tran_no,2,202,$_arr->user_amount,'订单结算支出,订单号:'.$order->order_id);
                      //记录公司账户收入
                      $base_acount_num=$_arr->acount_type==1?1:3;//如果用的现金账户 计入企业现金帐 如果是虚拟充值记录
                      Account::record_base($base_acount_num,$tran_no,1,102,$_arr->user_amount,'订单结算收入,订单号:'.$order->order_id);
                    }
                    OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                  }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                  }                  
              }else{
                  DB::rollback();
                  $response = Lang::get("scs_error.order_user_notpay_40039");
                  return $response;
              }
            }

            if($user->type == 2 && $pay_type== 6 ){//企业挂账
                // $account = UserAccount::where('user_id',$order->user_id)->first();
                $c=Companys::find($user->id);
                $check=Companys::accountDayStatus($c);
                if($check["day_status"]=='逾期（禁止挂帐）'){
                  DB::rollback();
                  $response = Lang::get("scs_error.order_user_notpay_40111");
                  return $response;
                }

                $uad=UserAccountDeatails::where("user_id",$user->id)->where("acount_type",3)->first();
                if(($uad->balance + $uad->credit) > $order_amount){
                  // //记录用户支出
                  // Account::record($order->user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
                  // //记录公司账户收入
                  // Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');
                  // //记录订单账务关系

                  //挂账 只记录用户虚拟账户支出 挂账收回时候 记录平台收入  挂账退货 没收回退货会用户帐 ，收回之后退货，记录不回用户帐记录企业支出
                  //挂账账户是 平台门店传 0
                  Account::record($order->user_id,0,3,$tran_no,2,202,$order_amount,'订单结算支出,订单号:'.$order->order_id);

                  OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                }
            }

            
          }

          $order->payable_amount=$temp_amount;
          $order->pay_type=sizeof($pay_array)==1?$pay_array[0]["pay_type"]:9;
          $order->status=$order_status;
          $order->pay_user_id=$order->user_id;
          $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
          $order->save();
          return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
      });

    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-15 13:04:33
     * @Description: 订单支付新接口
     *需要保证传入参数 正确
     */
    public static function order_pay($order_id,$pay_type,$pay_amount,$sc_user_id,$create_type,$driver_id,$source=1){
      return DB::transaction(function () use ($order_id,$pay_type,$pay_amount,$sc_user_id,$create_type,$driver_id,$source) {
        $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();
        if(in_array($order->status,array(1117,1217,1417))){//是否已结算
          DB::rollback();
          $response = Lang::get("scs_error.order_status_error_40040");
          return $response;
        }
        $temp_pay=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(1,5,7))->where("pay_type",$pay_type)->first();
        if($temp_pay){
          DB::rollback();
          $response = Lang::get("scs_error.order_pay_record_40131");
          return $response;
        }

        $order_amount=$pay_amount*100;
        $temp_amount=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,5,7))->sum("amount");
        if(bcsub($order->balance_amount, $order->payable_amount,0)<($order_amount+$temp_amount)){
          DB::rollback();
          $response = Lang::get("scs_error.order_pay_record_40113");
          return $response;
        }
        //如果没有支付用户则  支付用户为
        if($order->pay_user_id==0||$order->pay_user_id==null){
          $user = Users::find($order->user_id);
        }else{
          $user = Users::find($order->pay_user_id);
        }
        $account = UserAccount::where('user_id',$user->id)->first();
        $tran_no = date('YmdHis',time()).Common::generateCode(8);          
        //各种进行判断
        if($user->type == 1 && $pay_type== 6){//如果是个人用户不能用挂账
          DB::rollback();
          $response = Lang::get("scs_error.order_user_notpay_40038");
          return $response;
        }
        if($user->id == 1000000000 && $pay_type == 8){//特殊账户不能余额
            DB::rollback();
            $response = Lang::get("scs_error.order_user_notpay_40059");
            return $response;
        }
        //验证完成订单支付
        $o_p=new OrderPay;
        $o_p->user_id=$user->id;
        $o_p->order_id=$order_id;
        $o_p->pay_type=$pay_type;
        $o_p->amount=$order_amount;
        $o_p->status=1;
        $o_p->create_by=$sc_user_id;
        $o_p->tran_no=$tran_no;
        $o_p->create_type=$create_type;
        $o_p->implement_time=Common::currentTimeString();
        $o_p->save();
        if($source==1){//如果是系统 支付
          switch ($pay_type) {
            case 1://银行卡
            case 2://支付宝
            case 3://微信
            case 7://现金            
            case 11://线下支票
              //记录用户充值 不记录充值记录  只记录流水
              Account::record($user->id,$order->shop_id,1,$tran_no,1,102,$order_amount,'订单结算充值,订单号:'.$order->order_id);
              //记录用户支出
              Account::record($user->id,$order->shop_id,1,$tran_no,2,202,$order_amount,'订单结算支出,订单号:'.$order->order_id);
              //记录公司账户收入
              Account::record_base('1',$tran_no,1,102,$order_amount,'订单结算收入,订单号:'.$order->order_id);
              //记录订单账务关系
              OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
              break;
            case 8://个人余额 暂时不判断 因为个人 余额现在都为空 新版本判断用户余额
              $uad_balance=UserAccountDeatails::where("user_id",$user->id)->whereIn("acount_type",array(1,2))->sum("balance");   
                if(($uad_balance) >= $order_amount){
                  $arr=AcountUserRecharge::getUseRecharge($order->shop_id,$user->id,$order_amount,2,"asc");
                  if(sizeof($arr)>0){
                    foreach ($arr as $_arr) {
                      //记录了用户的充值消费记录
                      $aurs=new AcountUserRechargeSpend;
                      $aurs->aurr_id=$_arr->id;
                      $aurs->user_id=$order->user_id;
                      $aurs->buss_id=$o_p->id;
                      $aurs->type=1;
                      $aurs->amount=$_arr->user_amount;
                      $aurs->status=1;
                      $aurs->tran_no=$tran_no;
                      $aurs->shop_id=$order->shop_id;
                      $aurs->implement_time=date("Y-m-d H:i:s",time());
                      $aurs->save();
                      //更改充值记录消费的记录
                      AcountUserRecharge::where('id',$_arr->id)->update(array('current_amount'=> $_arr->current_amount -$_arr->user_amount,));
                      //记录个人 各种账户余额
                      Account::record($user->id,$_arr->shop_id,$_arr->acount_type,$tran_no,2,202,$_arr->user_amount,'订单结算支出,订单号:'.$order->order_id);
                      //记录公司账户收入
                      $base_acount_num=$_arr->acount_type==1?1:3;//如果用的现金账户 计入企业现金帐 如果是虚拟充值记录
                      Account::record_base($base_acount_num,$tran_no,1,102,$_arr->user_amount,'订单结算收入,订单号:'.$order->order_id);
                    }
                    OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                  }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                  }                  
                }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                }
              break;
            case 6://企业挂账
              $c=Companys::find($user->id);
              $check=Companys::accountDayStatus($c);
              if($check["day_status"]=='逾期（禁止挂帐）'){
                DB::rollback();
                $response = Lang::get("scs_error.order_user_notpay_40111");
                return $response;
              }
              $uad=UserAccountDeatails::where("user_id",$user->id)->where("acount_type",3)->first();
              if(($uad->balance + $uad->credit) > $order_amount){
                //挂账 只记录用户虚拟账户支出 挂账收回时候 记录平台收入  挂账退货 没收回退货会用户帐 ，收回之后退货，记录不回用户帐记录企业支出
                //挂账账户是 平台门店传 0
                Account::record($user->id,0,3,$tran_no,2,202,$order_amount,'订单结算支出,订单号:'.$order->order_id);
                OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
              }else{
                  DB::rollback();
                  $response = Lang::get("scs_error.order_user_notpay_40039");
                  return $response;
              }
              break;            
            default:
              # code...
              break;
          }
        }else{// 如果是pos支付
          //支付设备
          $mpd=MaintenancePosDevice::where("id",$driver_id)->where('shop_id',$order->shop_id)->where('status',1)->first();
          if(is_null($mpd)){
            DB::rollback();
            $response = Lang::get("scs_error.order_pay_driver_error_40116");
            return $response;
          }
          $call_scan=($pay_type==20?1:0); 
          $temp_pay_type=($pay_type==20?0:$pay_type);
          // OrderPay::where("id",$o_p->id)->update(array("status"=>5,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
          //调用智能pos 支付
          $w=WposRecord::prepareOrder(2,$order_id,$o_p->id,$order_amount,$user->id,$order->shop_id,$mpd->device_no,$sc_user_id,$temp_pay_type,$call_scan);
          if($w){
            OrderPay::where("id",$o_p->id)->update(array("status"=>5,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
          }else{
            OrderPay::where("id",$o_p->id)->update(array("status"=>2,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
            $response = Lang::get("scs_error.order_pay_driver_error_40116");
            return $response;
          }
          $order_amount=0;//修改支付金额为0 回掉产生才算是支付完成
        }
        
        $op_arr=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5))->get();
        $order->payable_amount=$order->payable_amount+$order_amount;
        $order->pay_type=sizeof($op_arr)==1?$pay_type:9;
        $order->pay_user_id=$user->id;
        // $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
        $order->save();


        return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
      });

    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-10-25 14:14:23
     * @Description: 用于订单代付的接口
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-06-14 18:03:24
     * @Description: 接口废弃
     */
    public static function otherPay($order_id,$pay_array,$pay_user_id,$sc_user_id,$create_type,$order_status){
      return DB::transaction(function () use ($order_id,$pay_array,$pay_user_id,$sc_user_id,$create_type,$order_status) {
          $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();
         if(in_array($order->status,array(1117,1217,1417))){//是否已结算
              DB::rollback();
              $response = Lang::get("scs_error.order_status_error_40040");
              return $response;
          }
          // $user = Users::where('id',$pay_user_id)->where('status',1)->first();
          $user = Users::find($pay_user_id);
          $account = UserAccount::where('user_id',$pay_user_id)->first();
          $temp_amount=0;
          foreach ($pay_array as $_pa) {
            // $tran_no = date('Ymd',time()).Common::generateCode();
            $tran_no = date('YmdHis',time()).Common::generateCode(8);
            $temp_amount+=$_pa["amount"]*100;
            $order_amount=$_pa["amount"]*100;
            $pay_type=$_pa["pay_type"];
            //各种进行判断
            if($user->type == 1 && $pay_type== 6){
                DB::rollback();
                $response = Lang::get("scs_error.order_user_notpay_40038");
                return $response;
            }
            if($pay_user_id == 1000000000 && $pay_type == 8){
                DB::rollback();
                $response = Lang::get("scs_error.order_user_notpay_40059");
                return $response;
            }
            $o_p=new OrderPay;
            $o_p->order_id=$order_id;
            $o_p->pay_type=$pay_type;
            $o_p->amount=$order_amount;
            $o_p->status=1;
            $o_p->create_by=$sc_user_id;
            $o_p->tran_no=$tran_no;
            $o_p->create_type=$create_type;
            $o_p->save();
            if($pay_type== 1||$pay_type== 7){//现金 或者银行卡支付
                // //记录用户充值
                // Account::record($pay_user_id,$tran_no,1,'01',$order_amount,'订单结算充值');
                // //记录用户支出
                // Account::record($pay_user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
                // //记录公司账户收入
                // Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');

                //记录用户充值 不记录充值记录  只记录流水
                Account::record($pay_user_id,$order->shop_id,1,$tran_no,1,102,$order_amount,'订单结算充值,订单号:'.$order->order_id);
                //记录用户支出
                Account::record($pay_user_id,$order->shop_id,1,$tran_no,2,202,$order_amount,'订单结算支出,订单号:'.$order->order_id);
                //记录公司账户收入
                Account::record_base('1',$tran_no,1,102,$order_amount,'订单结算收入,订单号:'.$order->order_id);

                //记录订单账务关系
                OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
            }
            if($pay_type == 8){//个人余额 暂时不判断 因为个人 余额现在都为空
              //记录用户支出
              // Account::record($pay_user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
              // //记录公司账户收入
              // Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');
              // //记录订单账务关系
              // OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));

              $uad_balance=UserAccountDeatails::where("user_id",$pay_user_id)->whereIn("acount_type",array(1,2))->sum("balance");   
              if(($uad_balance) >= $order_amount){
                  $arr=AcountUserRecharge::getUseRecharge($order->shop_id,$pay_user_id,$order_amount,2,"asc");
                  if(sizeof($arr)>0){
                    foreach ($arr as $_arr) {
                      //记录了用户的充值消费记录
                      $aurs=new AcountUserRechargeSpend;
                      $aurs->aurr_id=$_arr->id;
                      $aurs->user_id=$pay_user_id;
                      $aurs->buss_id=$o_p->id;
                      $aurs->type=1;
                      $aurs->amount=$_arr->user_amount;
                      $aurs->status=1;
                      $aurs->tran_no=$tran_no;
                      $aurs->shop_id=$order->shop_id;
                      $aurs->implement_time=date("Y-m-d H:i:s",time());
                      $aurs->save();
                      //更改充值记录消费的记录
                      AcountUserRecharge::where('id',$_arr->id)->update(array('current_amount'=> $_arr->current_amount -$_arr->user_amount,));
                      //记录个人 各种账户余额
                      Account::record($pay_user_id,$_arr->shop_id,$_arr->acount_type,$tran_no,2,202,$_arr->user_amount,'订单结算支出,订单号:'.$order->order_id);
                      //记录公司账户收入
                      $base_acount_num=$_arr->acount_type==1?1:3;//如果用的现金账户 计入企业现金帐 如果是虚拟充值记录
                      Account::record_base($base_acount_num,$tran_no,1,102,$_arr->user_amount,'订单结算收入,订单号:'.$order->order_id);
                    }
                    OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                  }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                  }                  
              }else{
                  DB::rollback();
                  $response = Lang::get("scs_error.order_user_notpay_40039");
                  return $response;
              }
            }

            if($user->type == 2 && $pay_type== 6){//企业挂账
                // $account = UserAccount::where('user_id',$order->user_id)->first();
                // if(($account->balance + $account->credit) > 0){
                //   //记录用户支出
                //   Account::record($pay_user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
                //   //记录公司账户收入
                //   Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');
                //   //记录订单账务关系
                //   OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                // }else{
                //     DB::rollback();
                //     $response = Lang::get("scs_error.order_user_notpay_40039");
                //     return $response;
                // }
                $c=Companys::find($pay_user_id);
                $check=Companys::accountDayStatus($c);
                if($check["day_status"]=='逾期（禁止挂帐）'){
                  DB::rollback();
                  $response = Lang::get("scs_error.order_user_notpay_40111");
                  return $response;
                }
                $uad=UserAccountDeatails::where("user_id",$pay_user_id)->where("acount_type",3)->first();
                if(($uad->balance + $uad->credit) > $order_amount){
                  // //记录用户支出
                  // Account::record($order->user_id,$tran_no,2,'02',$order_amount,'订单结算支出');
                  // //记录公司账户收入
                  // Account::record_base('1',$tran_no,1,'01',$order_amount,'订单结算收入');
                  // //记录订单账务关系

                  //挂账 只记录用户虚拟账户支出 挂账收回时候 记录平台收入  挂账退货 没收回退货会用户帐 ，收回之后退货，记录不回用户帐记录企业支出
                  //挂账账户是 平台门店传 0
                  Account::record($pay_user_id,0,3,$tran_no,2,202,$order_amount,'订单结算支出,订单号:'.$order->order_id);

                  OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                }
            }            
          }

          $order->payable_amount=$temp_amount;
          $order->pay_type=sizeof($pay_array)==1?$pay_array[0]["pay_type"]:9;
          $order->status=$order_status;
          $order->paymentp_type=1;
          $order->pay_user_id=$pay_user_id;
          $order->pay_time=date("Y-m-d H:i:s",time()+Config::get("config.report_time_diff"));
          $order->save();
          return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
      });

    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-10 11:03:40
     * @Description: 用于订单退款的接口
     */
    public static function refund($return_order_id,$sc_user_id,$create_type){
      return DB::transaction(function () use ($return_order_id,$sc_user_id,$create_type) {
          $ro=ReturnOrder::find($return_order_id);
          $ror=ReturnOrderRecord::where("return_order_id",$return_order_id)->get();
          $order=Orders::find($ro->order_id);
          // $user = Users::where('id',$order->user_id)->where('status',1)->first();
          $user = Users::find($order->pay_user_id);
          foreach ($ror as $_ror) {
            // $tran_no = date('Ymd',time()).Common::generateCode();
            $tran_no = date('YmdHis',time()).Common::generateCode(8);
            $order_amount=$_ror["amount"];
            $pay_type=$_ror["pay_type"];
            //各种进行判断
            if($pay_type== 1 ||$pay_type== 2 ||$pay_type== 3 || $pay_type== 7 || $pay_type== 11){//现金 或者银行卡支付
                //记录公司账户收入
                // Account::record_base('1',$tran_no,2,'02',$order_amount,'订单退货支出');


                Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,116,$order_amount,'订单退单收入,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
                //记录用户收入
                Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,216,$order_amount,'订单退单支出,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
                //记录公司账户支出
                Account::record_base('1',$tran_no,2,216,$order_amount,'订单退单支出,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
                //记录订单账务关系
                OrderAccount::insert(array('order_id' => $ro->id,'tran_no' => $tran_no,'type' => 2));
            }else if($pay_type == 8){//个人余额 暂时不判断 因为个人 余额现在都为空
                //记录用户支出
                // Account::record($order->user_id,$tran_no,1,'0103',$order_amount,'订单退货收入');
                // //记录公司账户收入
                // Account::record_base('1',$tran_no,2,'02',$order_amount,'订单退货支出');
                // //记录订单账务关系
                // OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                $op=OrderPay::where("order_id",$ro->order_id)->where("pay_type",8)->where("status",1)->first();
                $arr=AcountUserRechargeSpend::getUseRecharge($op->id,$order_amount,1);
                  if(sizeof($arr)>0){
                    foreach ($arr as $_arr) {
                      //记录了用户消费退款记录
                      $aurs=new AcountUserRechargeSpendRe;
                      $aurs->aurr_id=$_arr->aurr_id;
                      $aurs->user_id=$order->pay_user_id;//谁使用
                      $aurs->aurr_sp_id=$_arr->id;                      
                      $aurs->buss_id=$_ror->id;
                      $aurs->type=1;
                      $aurs->amount=$_arr->user_amount;
                      $aurs->status=1;
                      $aurs->tran_no=$tran_no;
                      $aurs->shop_id=$order->shop_id;
                      $aurs->implement_time=date("Y-m-d H:i:s",time());
                      $aurs->save();
                      //更改充值记录
                      DB::update('update acount_user_recharge_record set current_amount = current_amount+? where id = ?', array($_arr->user_amount,$_arr->aurr_id));
                      //更改充值记录消费记录
                      AcountUserRechargeSpend::where('id',$_arr->id)->update(array('return_amount'=> $_arr->return_amount +$_arr->user_amount,));
                      //记录个人 各种账户余额
                      $sac=AcountUserRecharge::find($_arr->aurr_id);
                      Account::record($order->pay_user_id,$sac->shop_id,$_arr->acount_type,$tran_no,1,116,$_arr->user_amount,'订单退单收入,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
                      //记录公司账户支出
                      $base_acount_num=$_arr->acount_type==1?1:3;//如果用的现金账户 计入企业现金帐 如果是虚拟充值记录
                      Account::record_base($base_acount_num,$tran_no,2,216,$_arr->user_amount,'订单退单支出,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
                    }
                    OrderAccount::insert(array('order_id' => $ro->id,'tran_no' => $tran_no,'type' => 2));
                  }else{
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40039");
                    return $response;
                  } 

            }else if( $pay_type== 6){//企业挂账  只记录 个人消费  财务收入 在应收收回 收回时 计算 应收和退款计算
                // if($order->verify_status==0){
                //     //记录用户支出
                //     Account::record($order->user_id,$tran_no,1,'0103',$order_amount,'订单退货充值');
                //     //记录公司账户收入
                //     Account::record_base('1',$tran_no,2,'02',$order_amount,'订单退货支出');
                //     //记录订单账务关系
                //     OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                // }else{
                //     //记录公司账户收入
                //     Account::record_base('1',$tran_no,2,'02',$order_amount,'订单退货支出');
                //     //记录订单账务关系
                //     OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                // }
                Account::record($order->pay_user_id,0,3,$tran_no,1,116,$order_amount,'订单退单收入,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
                OrderAccount::insert(array('order_id' => $ro->id,'tran_no' => $tran_no,'type' => 2));
            }else{
              Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,116,$order_amount,'订单退单收入,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
              //记录用户收入
              Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,216,$order_amount,'订单退单支出,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
              //记录公司账户支出
              Account::record_base('1',$tran_no,2,216,$order_amount,'订单退单支出,订单退货单号:'.$ro->id.',订单号:'.$ro->order_id);
              //记录订单账务关系
              OrderAccount::insert(array('order_id' => $ro->id,'tran_no' => $tran_no,'type' => 2));
            }

            $o_p=new OrderReturn;
            $o_p->order_id=$order->order_id;
            $o_p->pay_type=$pay_type;
            $o_p->amount=$order_amount;
            $o_p->status=1;
            $o_p->create_by=$sc_user_id;
            $o_p->tran_no=$tran_no;
            $o_p->create_type=$create_type;
            $o_p->save();
          }

          $temp_amount=ReturnOrderRecord::where("return_order_id",$return_order_id)->whereIn("pay_type",OrderPay::$ei_pay_type)->sum("amount");
          if($temp_amount>0){
              $temp_order=$order->order_type==1?1:2;
              $mc=MemberCoefficient::where("source",$temp_order)->where("status",1)->first();
              $ms=MaintenanceShops::find($order->shop_id);

              UserIntegralFlow::record($order->pay_user_id,$order->shop_id,$ro->id,2,$order->order_type==1?2001:2002,floor($temp_amount*$mc->integral*$ms->integral/100),'订单退款扣除积分');
              UserExperienceFlow::record($order->pay_user_id,$order->shop_id,$ro->id,2,$order->order_type==1?2001:2002,floor($temp_amount*$mc->experience*$ms->experience/100),'订单退款扣除经验');
              Users::checkMember($order->pay_user_id);
          }

          return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
      });
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-07-26 15:49:50
     * @Description: 用于订单反算的 model
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-08-02 15:16:07
     * @Description: 废弃的方法 不在使用
     */
    // public static function inverse($order_id){
    //   return DB::transaction(function () use ($order_id) {
    //     $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();
    //     $order_product=OrderProduct::where("order_id",$order_id)->where("status",1)->lockForUpdate()->get();
    //     $dis_all=$order->amount-$order->payable_amount-$order->discount;
    //     if($order->amount==0){
    //       return ;
    //     }
    //     foreach ($order_product as $_op) {
    //       $dis=$_op->amount/$order->amount;
    //       $_op->counter_amount=$_op->amount-$_op->discount-$dis*$dis_all;
    //       $_op->save();
    //       switch ($_op->product_type) {
    //         case 'enterprise':
    //           $opep=OrderProductEsPackage::where("order_product_id",$_op->id)->get();
    //           $all_amount=OrderProductEsPackage::where("order_product_id",$_op->id)->sum("amount");
    //           foreach ($opep as $key => $value){
    //               $order_dis=$value->amount/$all_amount;//算出 该产品包占用了该企业产品的多少份额
    //               $temp_packamount=$_op->amount*$order_dis;//算出改包 实际在该产品中的价格
    //               $dis=$temp_packamount/$order->amount;//算出该产品包 分的的折扣减免金额
    //               $value->counter_amount=$temp_packamount-$dis*$dis_all;
    //               $value->save();
    //               $opei=OrderProductEsItem::where("order_product_package_id",$value->id)->get();
    //               foreach ($opei as $_item) {
    //                   if($_item->type==1){//如果是耗材
    //                     $dis=$_item->amount*$_item->num/$value->amount;//耗材 在该包中占比多少
    //                     $_item->counter_amount=($value->counter_amount*$dis)/$_item->num;
    //                   }else{//如果是服务
    //                     $dis=$_item->amount/$value->amount;
    //                     $_item->counter_amount=$value->counter_amount*$dis;
    //                   }
    //                   $_item->save();
    //               }                  
    //           }
    //           break;
    //       case 'activity':
    //           $opacp=OrderProductAcPackage::where("order_product_id",$_op->id)->get();
    //           $all_amount=OrderProductAcPackage::where("order_product_id",$_op->id)->sum("amount");
    //           foreach ($opacp as $key => $value){
    //               $order_dis=$value->amount/$all_amount;//算出 该产品包占用了该企业产品的多少份额
    //               $temp_packamount=$_op->amount*$order_dis;//算出改包 实际在该产品中的价格
    //               $dis=$temp_packamount/$order->amount;//算出该产品包 分的的折扣减免金额
    //               $value->counter_amount=$temp_packamount-$dis*$dis_all;
    //               $value->save();
    //               $opaci=OrderProductAcItem::where("order_product_package_id",$value->id)->get();
    //               foreach ($opaci as $_item) {
    //                   if($_item->type==1){//如果是耗材
    //                       $dis=$_item->amount*$_item->num/$value->amount;//耗材 在该包中占比多少
    //                       $_item->counter_amount=($value->counter_amount*$dis)/$_item->num;
    //                   }else{//如果是服务
    //                       $dis=$_item->amount/$value->amount;
    //                       $_item->counter_amount=$value->counter_amount*$dis;
    //                   }
    //                   $_item->save();
    //               }
    //           }
    //           break;
    //         case 'promotion':
    //           $opp=OrderProductPackage::where("order_product_id",$_op->id)->get();
    //           foreach ($opp as $key => $value){
    //               $dis=$value->amount/$order->amount;
    //               $value->counter_amount=$value->amount-$dis*$dis_all;
    //               $value->save();
    //               $opi=OrderProductItem::where("order_product_package_id",$value->id)->get();
    //               foreach ($opi as $_item) {
    //                 if($_item->type==1){
    //                   $dis=$_item->amount*$_item->num/$value->counter_amount;//看看占比多少
    //                   $_item->counter_amount=($value->counter_amount*$dis)/$_item->num;
    //                 }else{
    //                   $dis=$_item->amount/$value->counter_amount;
    //                   $_item->counter_amount=$value->counter_amount*$dis;
    //                 }
    //                 $_item->save();
    //               }
    //           }
    //           break;
    //         case 'base':
    //           $opp=OrderProductBaseItem::where("order_product_package_id",$_op->id)->get();
    //           foreach ($opp as $_item) {
    //               if($_item->type==1){
    //                 $dis=$_item->amount*$_item->num/$order->amount;
    //                 $_item->counter_amount=$_item->amount*$_item->discount-$dis*$dis_all/$_item->num;
    //               }else{
    //                 $dis=$_item->amount/$order->amount;
    //                 $_item->counter_amount=$_item->amount*$_item->discount-$dis*$dis_all;
    //               }
    //               $_item->save();                        
    //           }
    //           break;
    //         case 'non_standard':
    //           $opn=OrderProductNonStandard::where("order_product_id",$_op->id)->where('status',1)->get();
    //           foreach ($opn as $_item) {
    //               if($_item->service_type==1){
    //                 $dis=$_item->amount*$_item->num/$order->amount;
    //                 $_item->counter_amount=$_item->amount*$_item->discount-$dis*$dis_all/$_item->num;  
    //               }else{
    //                 $dis=$_item->amount/$order->amount;
    //                 $_item->counter_amount=$_item->amount*$_item->discount-$dis*$dis_all;
    //               }
    //               $_item->save();
    //           }
    //           break;
    //       }
    //     }         
    //   });
    // }
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-8 15:41:32
     * @Description: 检查是否已出过库(单品)
     */
    public static function isOut($order_id,$order_product_item_id,$product_type){
        if($product_type =='promotion'){
            $opi=OrderProductItem::find($order_product_item_id);
            if($opi){
                $moo=MaintenanceOutOrder::where('product_type','promotion')->where('product_item_id',$order_product_item_id)->whereIn('status',array(2))->first();
                if($moo){
                    return true;
                }
            }
        }else if($product_type =='enterprise'){
            $opei=OrderProductEsItem::find($order_product_item_id);
            if($opei){
                $moo=MaintenanceOutOrder::where('product_type','enterprise')->where('product_item_id',$order_product_item_id)->whereIn('status',array(2))->first();
                if($moo){
                    return true;
                }
            }
        }else if($product_type =='activity'){
            $opaci=OrderProductAcItem::find($order_product_item_id);
            if($opaci){
                $moo=MaintenanceOutOrder::where('product_type','activity')->where('product_item_id',$order_product_item_id)->whereIn('status',array(2))->first();
                if($moo){
                    return true;
                }
            }
        }else if($product_type =='base'){
            $opbi=OrderProductBaseItem::find($order_product_item_id);
            if($opbi){
                $moo=MaintenanceOutOrder::where('product_type','base')->where('product_item_id',$order_product_item_id)->whereIn('status',array(2))->first();
                if($moo){
                    return true;
                }
            }
        }else if($product_type =='non_standard'){
            $opns=OrderProductNonStandard::where('id',$order_product_item_id)->where('status',1)->first();
            if($opns){
                // $op=OrderProduct::find($opns->order_product_id);
                $moo=MaintenanceOutOrder::where('product_type','non_standard')->where('product_item_id',$order_product_item_id)->whereIn('status',array(2))->first();
                if($moo){
                    return true;
                }
            }
        }else if($product_type =='service_card'){
            $opns=OrderProductScItem::find($order_product_item_id);
            if($opns){
                // $op=OrderProduct::find($opns->order_product_id);
                $moo=MaintenanceOutOrder::where('product_type','service_card')->where('product_item_id',$order_product_item_id)->whereIn('status',array(2))->first();
                if($moo){
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-24 16:06:20
     * @Description: 检查折扣是否符合
     */
    
    public static function isFitDiscount($order_id,$dis){
        $promotion_procut=$base_procut=$item=array();
        $order_products=OrderProduct::where("order_id",$order_id)->where("status",1)->where("coupon_discount",0)->get()->toArray();
        foreach ($order_products as $_op) {
            switch ($_op['product_type']) {
                case 'base':
                    $opp=OrderProductBaseItem::where("order_product_package_id",$_op['id'])->get()->toArray();
                    foreach ($opp as $key=>$_item) {
                        if($_item['discount']<$dis){
                            return false;
                        }
                    }
                    break;
                case 'non_standard':
                    $opn=OrderProductNonStandard::where("order_product_id",$_op['id'])->where('status',1)->get()->toArray();
                    foreach ($opn as $key=>$value) {
                        if($value['discount']<$dis){
                            return false;
                        }
                    }
                    break;
            }
        }
        return true;
    }



     /**
     * @Author:      lyt
     * @DateTime:    2016-07-26 15:49:50
     * @Description: 用于订单反算的 model
     */
    public static function inverseOrder($order_id){
      return DB::transaction(function () use ($order_id) {
        $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();
        $diyong_dis=OrderProduct::where("order_id",$order_id)->where("status",1)->sum("coupon_discount");//获取优惠在 产品包上的优惠金额
        $order_product=OrderProduct::where("order_id",$order_id)->where("status",1)->lockForUpdate()->get();
        $dis_all=$order->amount-$order->payable_amount-$order->discount-$diyong_dis-$order->service_card_amount;//获取 改价优惠 ，抹零优惠和 订单上优惠的金额
        $order_amount=$order->amount-$order->service_card_amount; //套餐卡类型包不参与均摊 这种包都是免费
        if($order->amount==0){
          return ;
        }
        $service_array=array();//用于订单所有的 工时的计算
        $all_services_amount=0;


        /**
         * step one  平均按照比例均摊
         */
        foreach ($order_product as $_op) {
          $product_amount=0;
          switch ($_op->product_type) {
            case 'enterprise':
              $opep=OrderProductEsPackage::where("order_product_id",$_op->id)->get();
              $all_amount=OrderProductEsPackage::where("order_product_id",$_op->id)->sum("amount");//包的总价
              foreach ($opep as $key => $value){                  
                  $package_amount=0;
                  $opei=OrderProductEsItem::where("order_product_package_id",$value->id)->get();
                  foreach ($opei as $_item) {
                      if($_item->type==1){//如果是耗材
                        if($all_amount*$_item->num==0 || $order_amount*$all_amount*$_item->num==0){
                            continue;
                        }
                        $temp_allamount=$_item->amount*$_item->num;//耗材 总共多少钱
                        //按照比例取整 获得应该卖多少钱取整
                        $temp_counter_amount=bcdiv(($temp_allamount*$_op->amount),($all_amount*$_item->num),2);
                        //减面多少钱
                        $temo_dis=bcdiv($_op->amount*$temp_allamount*$dis_all,$order_amount*$all_amount*$_item->num,2);  
                        $_item->counter_amount=round(bcsub($temp_counter_amount,$temo_dis,2));
                        $package_amount=$package_amount+($_item->counter_amount*$_item->num);
                      }else{//如果是服务
                          if($all_amount==0 || $order_amount*$all_amount==0){
                            continue;
                          }
                        // $temp_counter_amount=(int)floor(($_item->amount*$_op->amount)/$all_amount);
                        $temp_counter_amount=bcdiv($_item->amount*$_op->amount,$all_amount,2);
                        //减面多少钱
                        $temo_dis=bcdiv($_op->amount*$_item->amount*$dis_all,$order_amount*$all_amount,2);
                        $_item->counter_amount=round(bcsub($temp_counter_amount,$temo_dis,2));
                        $package_amount=$package_amount+$_item->counter_amount;
                        $service_array[]=array("type"=>"enterprise","amount"=>$_item->amount,"item_id"=>$_item->id,"use_amount"=>0);
                        $all_services_amount+=$_item->amount;
                      }
                      $_item->save();
                  }
                  $value->counter_amount=$package_amount;
                  $value->save();
                  $product_amount+=$package_amount;
              }              
              break;
            case 'activity':
              $opacp=OrderProductAcPackage::where("order_product_id",$_op->id)->get();
              $pa=ProductActivity::find($_op->product_id);
              if($pa->type==1){
                  $all_amount=OrderProductAcPackage::where("order_product_id",$_op->id)->sum("amount");//包的总价
                  foreach ($opacp as $key => $value){
                      $package_amount=0;
                      $opaci=OrderProductAcItem::where("order_product_package_id",$value->id)->get();
                      foreach ($opaci as $_item) {
                          if($_item->type==1){//如果是耗材
                              if($all_amount*$_item->num==0 || $order_amount*$all_amount*$_item->num==0){
                                  continue;
                              }
                              $temp_allamount=$_item->amount*$_item->num;//耗材 总共多少钱
                              //按照比例取整 获得应该卖多少钱取整
                              $temp_counter_amount=bcdiv(($temp_allamount*$_op->amount),($all_amount*$_item->num),2);
                              //减面多少钱
                              $temo_dis=bcdiv($_op->amount*$temp_allamount*$dis_all,$order_amount*$all_amount*$_item->num,2);
                              $_item->counter_amount=round(bcsub($temp_counter_amount,$temo_dis,2));
                              $package_amount=$package_amount+($_item->counter_amount*$_item->num);
                          }else{//如果是服务
                              if($all_amount==0 || $order_amount*$all_amount==0){
                                  continue;
                              }
                              // $temp_counter_amount=(int)floor(($_item->amount*$_op->amount)/$all_amount);
                              $temp_counter_amount=bcdiv($_item->amount*$_op->amount,$all_amount,2);
                              //减面多少钱
                              $temo_dis=bcdiv($_op->amount*$_item->amount*$dis_all,$order_amount*$all_amount,2);
                              $_item->counter_amount=round(bcsub($temp_counter_amount,$temo_dis,2));
                              $package_amount=$package_amount+$_item->counter_amount;
                              $service_array[]=array("type"=>"activity","amount"=>$_item->amount,"item_id"=>$_item->id,"use_amount"=>0);
                              $all_services_amount+=$_item->amount;
                          }
                          $_item->save();
                      }
                      $value->counter_amount=$package_amount;
                      $value->save();
                      $product_amount+=$package_amount;
                  }
              }else{
                  $opacp=OrderProductAcPackage::where("order_product_id",$_op->id)->get();
                  foreach ($opacp as $key => $value){
                      $opaci=OrderProductAcItem::where("order_product_package_id",$value->id)->get();
                      $package_amount=0;
                      foreach ($opaci as $_item) {
                          if($_item->type==1){
                              if($order_amount*$_item->num==0){
                                  continue;
                              }
                            $temp_allamount=$_item->amount*$_item->num;//耗材 总共多少钱
                            //减免的 额度
                            
                            $temo_dis=bcdiv($temp_allamount*$dis_all,$order_amount*$_item->num,2);          
                            $temp_amount=bcmul($_item->amount,$_item->discount,2);
                            $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                            $package_amount=$package_amount+($_item->counter_amount*$_item->num);
                          }else{
                              if($order_amount==0){
                                  continue;
                              }
                            //减面多少钱
                            $temo_dis=bcdiv($_item->amount*$dis_all,$order_amount,2);
                            $temp_amount=bcmul($_item->amount,$_item->discount,2);
                            $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                            $package_amount=$package_amount+$_item->counter_amount;
                            $service_array[]=array("type"=>"activity","amount"=>$_item->amount,"item_id"=>$_item->id,"use_amount"=>0);
                            $all_services_amount+=$_item->amount;
                          }
                          $_item->save();                        
                      }
                      $value->counter_amount=$package_amount;
                      $value->save();
                      $product_amount+=$package_amount;
                  }
              }
              break;
            case 'promotion':
                break;
            case 'base':
              $opp=OrderProductBaseItem::where("order_product_package_id",$_op->id)->get();
              if($_op->coupon_discount<=0){
                  foreach ($opp as $_item) {
                      if($_item->type==1){
                          if($order_amount*$_item->num==0){
                              continue;
                          }
                        $temp_allamount=$_item->amount*$_item->num;//耗材 总共多少钱
                        //减免的 额度
                        
                        $temo_dis=bcdiv($temp_allamount*$dis_all,$order_amount*$_item->num,2);          
                        $temp_amount=bcmul($_item->amount,$_item->discount,2);
                        $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                        $product_amount=$product_amount+($_item->counter_amount*$_item->num);
    
                      }else{
                          if($order_amount==0){
                              continue;
                          }
                        //减面多少钱
                        $temo_dis=bcdiv($_item->amount*$dis_all,$order_amount,2);
                        $temp_amount=bcmul($_item->amount,$_item->discount,2);
                        $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                        $product_amount=$product_amount+$_item->counter_amount;
                        $service_array[]=array("type"=>"base","amount"=>$_item->amount,"item_id"=>$_item->id,"use_amount"=>0);
                        $all_services_amount+=$_item->amount;
                      }
                      $_item->save();                        
                  }
              }else{
                  foreach ($opp as $_item) {
                      if($_item->type==1){
                        if($order_amount*$_item->num==0){
                            continue;
                        }
                        $temp_allamount=$_item->amount*$_item->num;//耗材 总共多少钱
                        //减免的 额度                        
                        $temo_dis=bcdiv($temp_allamount*$dis_all,$order_amount*$_item->num,2);                          
                        //优惠券减免
                        $coupon_dis=bcdiv($temp_allamount*$_op->coupon_discount,$_op->amount*$_item->num,2);  

                        $temp_amount=bcsub($_item->amount,$coupon_dis,2);
                        $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                        $product_amount=$product_amount+($_item->counter_amount*$_item->num);
    
                      }else{
                          if($order_amount==0){
                              continue;
                          }
                        //减面多少钱
                        $temo_dis=bcdiv($_item->amount*$dis_all,$order_amount,2);
                        //优惠券减免
                        $coupon_dis=bcdiv($_item->amount*$_op->coupon_discount,$_op->amount,2);  

                        $temp_amount=bcsub($_item->amount,$coupon_dis,2);
                        $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                        $product_amount=$product_amount+$_item->counter_amount;
                        $service_array[]=array("type"=>"base","amount"=>$_item->amount,"item_id"=>$_item->id,"use_amount"=>0);
                        $all_services_amount+=$_item->amount;
                      }
                      $_item->save();                        
                  }
              }
              break;
            case 'service_card':
              $opp=OrderProductScItem::where("order_product_id",$_op->id)->get();              
                foreach ($opp as $_item) {                    
                  $_item->counter_amount=0;
                  $product_amount=$product_amount+0;
                  $_item->save();                        
                }              
              break;
            case 'non_standard':
              $opn=OrderProductNonStandard::where("order_product_id",$_op->id)->where('status',1)->get();
              foreach ($opn as $_item) {
                  if($_item->service_type==1){
                      if($order_amount*$_item->num==0){
                          continue;
                      }
                    // $dis=$_item->amount*$_item->num/$order->amount;
                    // $_item->counter_amount=$_item->amount*$_item->discount-$dis*$dis_all/$_item->num;  
                    $temp_allamount=$_item->amount*$_item->num;//耗材 总共多少钱
                    //减免的 额度   
                    $temo_dis=bcdiv($temp_allamount*$dis_all,$order_amount*$_item->num,2);   
                    $temp_amount=bcmul($_item->amount,$_item->discount,2);
                    $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                    $product_amount=$product_amount+($_item->counter_amount*$_item->num);
                  }else{
                      if($order_amount==0){
                          continue;
                      }
                    $temo_dis=bcdiv($_item->amount*$dis_all,$order_amount,2);
                    $temp_amount=bcmul($_item->amount,$_item->discount,2);
                    $_item->counter_amount=round(bcsub($temp_amount,$temo_dis,2));
                    $product_amount=$product_amount+$_item->counter_amount;
                    $service_array[]=array("type"=>"non_standard","amount"=>$_item->amount,"item_id"=>$_item->id,"use_amount"=>0);
                    $all_services_amount+=$_item->amount;
                  }
                  $_item->save();
              }
              break;
          }
          $_op->counter_amount=$product_amount;
          $_op->save();
        }

        /**
         * step two 查看剩余的为均摊完成的
         */     
        $temp_p=OrderProduct::where("order_id",$order_id)->where("status",1)->get();
        $order_product_amount=OrderProduct::where("order_id",$order_id)->where("status",1)->sum("counter_amount");//计算均的总价 
        if($order_product_amount!=$order->payable_amount){//说明没有平均均匀
          $cha_amount=$order->payable_amount-$order_product_amount;//还没有均出去的
          $sy_amount=$cha_amount;
          if($all_services_amount>0){
            foreach ($service_array as $key=>$_sa) {    
              if($key==count($service_array)-1){
                $_sa['use_amount']=$sy_amount;           
                $sy_amount=0;   
              }else{
                $temp_amout=(int)floor(($_sa['amount']*$cha_amount)/$all_services_amount);//该项目分到差值
                $_sa['use_amount']=$temp_amout;
                $sy_amount=$sy_amount-$temp_amout;
              }
              $service_array[$key]=$_sa;
            }
            foreach ($service_array as $_sa) {   
              switch ($_sa['type']) {
                case 'enterprise':
                  $opei=OrderProductEsItem::find($_sa['item_id']);
                  $opei->counter_amount=$opei->counter_amount+$_sa["use_amount"];
                  $opei->save();
                  $opep=OrderProductEsPackage::find($opei->order_product_package_id);
                  $opep->counter_amount=$opep->counter_amount+$_sa["use_amount"];
                  $opep->save();
                  $temo_op=OrderProduct::find($opep->order_product_id);
                  $temo_op->counter_amount=$temo_op->counter_amount+$_sa["use_amount"];
                  $temo_op->save();
                  break;
              case 'activity':
                  $opaci=OrderProductAcItem::find($_sa['item_id']);
                  $opaci->counter_amount=$opaci->counter_amount+$_sa["use_amount"];
                  $opaci->save();
                  $opacp=OrderProductAcPackage::find($opaci->order_product_package_id);
                  $opacp->counter_amount=$opacp->counter_amount+$_sa["use_amount"];
                  $opacp->save();
                  $temo_op=OrderProduct::find($opacp->order_product_id);
                  $temo_op->counter_amount=$temo_op->counter_amount+$_sa["use_amount"];
                  $temo_op->save();
                  break;
                case 'promotion':
                  break;
                case 'base':
                  $opp=OrderProductBaseItem::find($_sa['item_id']);
                  $opp->counter_amount=$opp->counter_amount+$_sa["use_amount"];
                  $opp->save();
                  $temo_op=OrderProduct::find($opp->order_product_package_id);
                  $temo_op->counter_amount=$temo_op->counter_amount+$_sa["use_amount"];
                  $temo_op->save();
                  break;
                case 'non_standard':    
                  $opp=OrderProductNonStandard::find($_sa['item_id']);
                  $opp->counter_amount=$opp->counter_amount+$_sa["use_amount"];
                  $opp->save();
                  $temo_op=OrderProduct::find($opp->order_product_id);
                  $temo_op->counter_amount=$temo_op->counter_amount+$_sa["use_amount"];
                  $temo_op->save();           
                  break;
              }
            }
          }
          

          if($sy_amount!=0){//说明没有  其他的 可供
            Log::info("订单：".$order_id." 均摊剩余:".$sy_amount);
          }


        }

      });
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-31 09:40:47
     * @Description: 订单价格每次变动都需要重新计算
     */
    public static function calculate($order_id){
        return DB::transaction(function () use ($order_id) {
            $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();
            $order_product=OrderProduct::where("order_id",$order_id)->where("status",1)->lockForUpdate()->get();

            //计算产品包
            $order_discount=0;//订单总优惠
            $service_card_amount=0;
            $order_amount=0;//订单总金额
            foreach ($order_product as $_op) {
                $order_product_discount=0;//单个产品包优惠金额
                $order_product_amount=0;//单个产品包金额
                switch ($_op->product_type) {
                    case 'enterprise':
                        $opep=OrderProductEsPackage::where("order_product_id",$_op->id)->get();
                        foreach($opep as $_opep){
                            $package_amount=0;//企业包中单个包的价格
                            $item=OrderProductEsItem::where('order_product_package_id',$_opep->id)->get();
                            foreach ($item as $key=>$_item) {
                                if($_item->type==1){
                                    $package_amount+=$_item->amount*$_item->num;
                                    $order_product_amount+=$_item->amount*$_item->num;
                                }else{
                                    $package_amount+=$_item->amount;
                                    $order_product_amount+=$_item->amount;
                                }
                            }
                            $_opep->amount=$package_amount;
                            $_opep->save();
                        }
                        $order_amount+=$_op->amount;
                        break;
                    case 'activity':
                        $pa=ProductActivity::find($_op->product_id);
                        if($pa->type==1){
                            $opacp=OrderProductAcPackage::where("order_product_id",$_op->id)->get();
                            foreach($opacp as $_opacp){
                                $package_amount=0;//企业包中单个包的价格
                                $item=OrderProductAcItem::where('order_product_package_id',$_opacp->id)->get();
                                foreach ($item as $key=>$_item) {
                                    if($_item->type==1){
                                        $package_amount+=$_item->amount*$_item->num;
                                        $order_product_amount+=$_item->amount*$_item->num;
                                    }else{
                                        $package_amount+=$_item->amount;
                                        $order_product_amount+=$_item->amount;
                                    }
                                }
                                $_opacp->amount=$package_amount;
                                $_opacp->save();
                            }
                            $order_amount+=$_op->amount;
                        }else{
                            $opacp=OrderProductAcPackage::where("order_product_id",$_op->id)->get();
                            foreach($opacp as $_opacp){
                                $package_amount=0;//活动包单个包的价格
                                $item=OrderProductAcItem::where('order_product_package_id',$_opacp->id)->get();
                                foreach ($item as $key=>$_item) {
                                    if($_item->type==1){
                                        $package_amount+=$_item->amount*$_item->num;
                                        $order_product_amount+=$_item->amount*$_item->num;
                                        $order_product_discount+=$_item->num*$_item->amount*(1-$_item->discount);
                                        $order_amount+=$_item->amount*$_item->num;
                                    }else{
                                        $package_amount+=$_item->amount;
                                        $order_product_amount+=$_item->amount;
                                        $order_product_discount+=$_item->amount*(1-$_item->discount);
                                        $order_amount+=$_item->amount;
                                    }
                                }
                                $_opacp->amount=$package_amount;
                                $_opacp->save();
                            }
                        }
                        break;
                    case 'promotion':
                        $opp=OrderProductPackage::where("order_product_id",$_op->id)->get();
                        foreach($opp as $_opp){
                            $package_amount=0;//推广包中单个包的价格
                            $item=OrderProductEsItem::where('order_product_package_id',$_opp->id)->get();
                            foreach ($item as $key=>$_item) {
                                if($_item->type==1){
                                    $package_amount+=$_item->amount*$_item->num;
                                    $order_product_amount+=$_item->amount*$_item->num;
                                    $order_amount+=$_item->amount*$_item->num;
                                }else{
                                    $package_amount+=$_item->amount;
                                    $order_product_amount+=$_item->amount;
                                    $order_amount+=$_item->amount;
                                }
                            }
                            $_opp->amount=$package_amount;
                            $_opp->save();
                        }
                        break;
                    case 'base':
                        $item=OrderProductBaseItem::where("order_product_package_id",$_op->id)->get();
                        foreach ($item as $key=>$_item) {
                            if($_item->type==1){
                                $order_product_amount+=$_item->amount*$_item->num;
                                if($_op->coupon_discount==0){
                                  $order_product_discount+=$_item->num*$_item->amount*(1-$_item->discount);
                                }
                                
                                $order_amount+=$_item->amount*$_item->num;
                            }else{
                                $order_product_amount+=$_item->amount;
                                if($_op->coupon_discount==0){
                                  $order_product_discount+=$_item->amount*(1-$_item->discount);
                                }                                
                                $order_amount+=$_item->amount;
                            }
                        }
                        break;
                    case 'service_card':
                        $item=OrderProductScItem::where("order_product_id",$_op->id)->get();
                        foreach ($item as $key=>$_item) {
                            if($_item->type==1){
                                $order_product_amount+=$_item->amount*$_item->num;  
                                $order_amount+=$_item->amount*$_item->num;
                                $service_card_amount+=$_item->amount*$_item->num;
                            }else{
                                $order_product_amount+=$_item->amount;                               
                                $order_amount+=$_item->amount;
                                $service_card_amount+=$_item->amount;
                            }
                        }
                        break;
                    case 'non_standard':
                        $item=OrderProductNonStandard::where("order_product_id",$_op->id)->where('status',1)->get();
                        foreach ($item as $key=>$_item) {
                            if($_item->service_type==1){
                                $order_product_amount+=$_item->amount*$_item->num;
                                $order_product_discount+=$_item->num*$_item->amount*(1-$_item->discount);
                                $order_amount+=$_item->amount*$_item->num;
                            }else{
                                $order_product_amount+=$_item->amount;
                                $order_product_discount+=$_item->amount*(1-$_item->discount);
                                $order_amount+=$_item->amount;
                            }
                        }
                        break;
    
                }
                $order_discount+=$order_product_discount;//每个产品包优惠相加得到订单总优惠
                
                if($_op->product_type!='enterprise'){
                    $_op->discount=$order_product_discount;
                    if($_op->product_type=='activity'){
                        $pa=ProductActivity::find($_op->product_id);
                        if($pa->type==2){
                            $_op->amount=$order_product_amount;
                        }
                    }else{
                        $_op->amount=$order_product_amount;
                    }
                    $_op->save();
                }
            }
            $order->discount=$order_discount;
            $order->service_card_amount=$service_card_amount;
            $balance=$order_amount-$order->discount_amount-$order_discount-$service_card_amount;
            $order->balance_amount=$balance>=0?$balance:0;
            $order->amount=$order_amount;
            $order->save();
        });
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-6 10:01:08
     * @Description: 是否可售
     */
    public static function isSale($item_id,$type=0){
        // if($type == 0){
            $si=SupplyItem::find($item_id);
            $scf=SupplyClassification::getClassification($si->supply_classification_id);
            // $scd=StatisticalClassifyDesc::find($scf->one_id);
            if(isset($scd) && $scd->one_is_sale==0){
                return true;
            }
        // }else{
        //     $sins=SupplyItemNonStandard::find($item_id);
        //     $scf=StatisticalClassification::getClassification($sins->st_classifi_id);
        //     $scd=StatisticalClassifyDesc::find($scf->one_id);
        //     if(isset($scd) && $scd->is_sale==0){
        //         return true;
        //     }
        // }
        return false;
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-13 09:57:45
     * @Description: 是否可创建订单
     */
    public static function createOrderBefore($car_no,$shop_id,$order_type){
//         if($order_type==1){
            $count=Orders::where('car_no',$car_no)->where('shop_id',$shop_id)->whereIn('status',array(1412,1215,1216,1416,1420))->where('order_source',14)->where('order_type',1)->count();
            if($count > 0){
                return true;
            }
//         }elseif($order_type==2){
//             $count=Orders::where('car_no',$car_no)->where('shop_id',$shop_id)->whereIn('status',array(1411))->where('order_source',14)->where('order_type',$order_type)->count();
//             if($count > 0){
//                 return true;
//             }
//         }
        return false;
    }
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-24 14:18:48
     * @Description: 修改优惠券状态
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-11 11:16:25
     * @Description: 修改接口 添加多个优惠券选择逻辑  如果是选中 更改选中优惠信息 清楚以前选中信息
     * 如果是取消选中 清楚以前选中信息
     */
    public static function changeCouponStatus($order_id,$status,$coupon_id,$user_id){
        return DB::transaction(function () use ($order_id,$status,$coupon_id,$user_id) {
            $response = array('code' => 0, 'msg' => 'ok');
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                return $response = Lang::get("scs_error.order_notexiet_40000");
            }
            if(in_array($orders->status,Orders::$complete)){
                return $response = Lang::get("scs_error.order_status_error_40026");
            }
            $coupon=Coupons::where('coupons.id',$coupon_id)
            ->leftJoin('coupon_base_info','coupon_base_info.id','=','coupons.coupon_base_info_id')
            ->select('coupons.id','coupons.code','coupons.status','coupons.coupon_base_info_id','coupons.end_date as end_date_1','coupon_base_info.end_date as end_date_2','coupon_base_info.date_type')
            ->lockForUpdate()
            ->first();
            if(is_null($coupon)){
                return $response = Lang::get("scs_error.order_coupon_error_40071");
            }
            if(!in_array($coupon->status,array(3,4))){ //说明优惠券状态不对
                return $response = Lang::get("scs_error.order_coupon_error_40073");
            }
            $cbi=CouponBaseInfo::find($coupon->coupon_base_info_id);
            if(!$cbi){ //优惠券基本信息不存在
                return $response = Lang::get("scs_error.order_coupon_error_40074");
            }
            if($cbi->limit_order==1){ //如果是上门
                return $response = Lang::get("scs_error.order_coupon_error_40092");
            }
            if($coupon->date_type==0){
                if(strtotime($coupon->end_date_2.' 23:59:59') < time()){ //优惠券已过期
                     return $response = Lang::get("scs_error.order_coupon_error_40075");
                }
            }else{
                if(strtotime($coupon->end_date_1.' 23:59:59') < time()){ //优惠券已过期
                    return $response = Lang::get("scs_error.order_coupon_error_40075");
                }
            }
            // $coupon_order=CouponOrderInfo::where('order_id',$orders->order_id)->where('coupon_id',$coupon_id)->where('val_status',1)->first();
            // if($coupon_order->status==$status){
            //   return $response = Lang::get("scs_error.order_coupon_error_40073");
            // }
            if($status==4){
              //判断限制类型           
              if($cbi->limit_type==1){//如果是金额限制
                  if($cbi->limit_amount>$orders->amount){
                      return $response = Lang::get("scs_error.order_coupon_error_40129");
                  }                
              }
              if($cbi->limit_type==2){//如果是服务限制
                  $limit_id=CouponPackLimit::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get();
                  $limit_arr=array();
                  foreach ($limit_id as $_li) {
                      $limit_arr[]=$_li->pack_id;
                  }
                  $top=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->select("product_id")->get();
                  $o_pid=array();
                  foreach ($top as $_top) {
                      $o_pid[$_top->product_id]=$_top->product_id;
                  }
                  $t=array_diff($limit_arr,array_values($o_pid));
                  if(sizeof($t)>0){//说明限制的服务订单中 又不存在的 
                      return $response = Lang::get("scs_error.order_coupon_error_40127");
                  }
              }
              //门店限制
              $cp=CouponShop::where("coupon_base_id",$cbi->id)->where("shop_id",$orders->shop_id)->where("status",1)->first();
              if(!$cp){ //该优惠券 不适合该门店
                  return $response = Lang::get("scs_error.order_coupon_error_40128");
              }
              switch ($cbi->type) {
                case 1://抵用券                        
                    if($cbi->amount>$orders->amount){//如果优惠金额大于订单今个 取消优惠券
                        return $response = Lang::get("scs_error.order_coupon_error_40080");
                    }
                    break;
                case 2://服务抵用卷
                case 4://服务减免券
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                    if(is_null($pack_arr)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    } 
                    $op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$pack_arr->pack_id)->where('product_type','base')->where("status",1)->where("amount",">=",$cbi->amount)->orderBy('id','asc')->first();
                    //此处判断 大于优惠金额的 满足优惠服务条件的，该订单的产品包 （由于类型2 服务抵用券优惠金额为0 所以对优惠类型2无影响，服务类型4 服务减免的服务价格不能小于 优惠金额 ）
                    if(is_null($op)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }                                          
                    break;
                case 3://实物抵用券
                    return $response = Lang::get("scs_error.order_coupon_error_40071");
                    break;                    
                case 5://服务折扣券 无金额限制
                    break;
              } 
            }

            //取消替他 正在使用的优惠券状态
            $check_coupon = CouponOrderInfo::where('order_id',$orders->order_id)->where('status',1)->where('val_status',1)->first();
            if($check_coupon){
              $check_cp=Coupons::find($check_coupon->coupon_id);
              $check_cbi=CouponBaseInfo::find($check_cp->coupon_base_info_id);              
              switch ($check_cbi->type) {
                case 2://服务抵用卷
                case 4://服务减免券
                case 5://服务折扣券
                    $check_op_ids=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->where("coupon_discount",">",0)->select("id")->get()->toArray();      
                    // $check_op->coupon_discount=0;
                    // $check_op->save();        
                    OrderProduct::whereIn("id",$check_op_ids)->update(array("coupon_discount"=>0));      
                    OrderProductBaseItem::whereIn('order_product_package_id',$check_op_ids)->update(array("discount"=>1));
                    break;
              } 
              CouponOrderInfo::where('order_id',$orders->order_id)->where('status',1)->update(array("status"=>0,"product_id"=>0));
              CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$check_cp->id)->delete();
              $check_cp->status=3;//如果取消则优惠券状态变为锁定
              $check_cp->save();
              $cr=new CouponRecords;
              $cr->order_id=$orders->order_id;
              $cr->status=0;
              $cr->coupon_id=$check_cp->id;
              $cr->operator=$orders->user_id;
              $cr->save();
            }    
            $orders->discount_amount=0;
            //如果是选中一个优惠券  计算选中优惠券的信息
            if($status==4){
              $temp_coupon_amount=0;
              $temp_op_id=array();
              switch ($cbi->type) {
                case 1://抵用券                
                  $temp_coupon_amount=$cbi->amount;
                  break;
                case 2://服务抵用卷
                  $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                  if(is_null($pack_arr)){
                      return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                  } 
                  $op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$pack_arr->pack_id)->where('product_type','base')->where("status",1)->orderBy('id','asc')->first();
                  if(is_null($op)){
                          DB::rollback();
                    return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                  }
                  $temp_coupon_amount=$op->amount;
                  //清空折扣信息
                  // if($op->discount > 0){
                  OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>1));                    
                  // }
                  $op->coupon_discount=$op->amount;
                  $op->discount=0;//折扣优惠清空
                  $op->save();
                  $temp_op_id[]=$op->id;
                  break;
                case 3://实物抵用券
                      DB::rollback();
                  return $response = Lang::get("scs_error.order_coupon_error_40071");
                  break;
                case 4://服务减免券
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                    if(is_null($pack_arr)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }
                    $op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$pack_arr->pack_id)->where('product_type','base')->where("status",1)->where("amount",">=",$cbi->amount)->orderBy('id','asc')->first();
                    if(is_null($op)){
                        DB::rollback();
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }
                    $temp_coupon_amount=$cbi->amount;
                    //清空折扣信息
                    // if($op->discount > 0){
                    OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>1));                    
                    // }
                    $op->coupon_discount=$cbi->amount;
                    $op->discount=0;//折扣优惠清空
                    $op->save();
                    $temp_op_id[]=$op->id;
                    break;
                case 5://服务折扣券
                    // $op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$cbi->pack_id)->where('product_type','base')->where("status",1)->orderBy('id','asc')->first();
                    // if(is_null($op)){
                    //     return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    // }
                    // $temp_coupon_amount=round($op->amount*(1-$cbi->discount));
                    // //清空折扣信息
                    // // if($op->discount > 0){
                    // OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>$cbi->discount));                    
                    // // }
                    // $op->coupon_discount=$temp_coupon_amount;
                    // $op->discount=0;//折扣优惠清空
                    // $op->save();
                    // $temp_op_id=$op->id;
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get()->toArray();                    
                    $ops=OrderProduct::where('order_id',$orders->order_id)->whereIn('product_id',$pack_arr)->where('product_type','base')->where("status",1)->get();
                    if(sizeof($ops)<=0){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }
                    foreach ($ops as $_op) {
                        $temp_coupon_amount+=round($_op->amount*(1-$cbi->discount));
                        OrderProductBaseItem::where('order_product_package_id',$_op->id)->update(array("discount"=>$cbi->discount));
                        $_op->coupon_discount=round($_op->amount*(1-$cbi->discount));
                        $_op->discount=0;//折扣优惠清空
                        $_op->save();
                        $temp_op_id[]=$_op->id;
                    } 


                    break;
              }   
              $coupon=Coupons::find($coupon_id);
              $coupon->status=4;//更改选中则优惠券状态为使用
              $coupon->use_time=date('Y-m-d H:i:s',time());
              $coupon->used_user_id=$orders->user_id;
              $coupon->save();                
              $orders->discount_amount=$temp_coupon_amount;
              CouponOrderInfo::where('order_id',$orders->order_id)->where('coupon_id',$coupon_id)->where('val_status',1)->update(array("status"=>1,"product_id"=>0));
              foreach ($temp_op_id as $t_o_p) {
                  $copi=new CouponOrderProductInfo;
                  $copi->order_id=$orders->order_id;
                  $copi->coupon_id=$coupon->id;
                  $copi->product_id=$t_o_p;
                  $copi->save();
              }
              $cr=new CouponRecords;
              $cr->order_id=$orders->order_id;
              $cr->status=1;
              $cr->coupon_id=$coupon->id;
              $cr->operator=$orders->user_id;
              $cr->save();
            }
            $orders->save(); 
            Orders::calculate($orders->order_id);            
            return $response;
        });
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-03-11 13:38:54
     * @Description: 删除优惠券 如果 这个优惠券是 使用中 取消再删除 如果是未使用的 更改状态回归优惠券状态
     */
    public static function deleteCopon($order_id,$coupon_id){
        return DB::transaction(function () use ($order_id,$coupon_id) {
            $response = array('code' => 0, 'msg' => 'ok');
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                return $response = Lang::get("scs_error.order_notexiet_40000");
            }
            if(in_array($orders->status,Orders::$complete)){
                return $response = Lang::get("scs_error.order_status_error_40026");
            }
            $coupon=Coupons::where('id',$coupon_id)->where('received_user_id',$orders->user_id)->first();
            if(is_null($coupon)){
                return $response = Lang::get("scs_error.order_coupon_error_40071");
            }
            if(!in_array($coupon->status,array(3,4))){ //说明优惠券状态不对
                return $response = Lang::get("scs_error.order_coupon_error_40073");
            }
            $cbi=CouponBaseInfo::find($coupon->coupon_base_info_id);
            if(!$cbi){ //优惠券基本信息不存在
                return $response = Lang::get("scs_error.order_coupon_error_40074");
            }            
            $coupon_order=CouponOrderInfo::where('order_id',$orders->order_id)->where('coupon_id',$coupon_id)->where('val_status',1)->first();
            if(!$coupon_order){
              return $response = Lang::get("scs_error.order_coupon_error_40073");
            }

            if($coupon_order->status==1){//如果正在使用
                switch ($cbi->type) {
                  case 2://服务抵用卷
                  case 4://服务减免券
                  case 5://服务折扣券
                      // $check_op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$cbi->pack_id)->where('product_type','base')->where("status",1)->where("coupon_discount",">",0)->first();      
                      // $check_op->coupon_discount=0;
                      // $check_op->save();              
                      // OrderProductBaseItem::where('order_product_package_id',$check_op->id)->update(array("discount"=>1));  
                      $check_op_ids=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->where("coupon_discount",">",0)->select("id")->get()->toArray();      
                      // $check_op->coupon_discount=0;
                      // $check_op->save();        
                      OrderProduct::whereIn("id",$check_op_ids)->update(array("coupon_discount"=>0));      
                      OrderProductBaseItem::whereIn('order_product_package_id',$check_op_ids)->update(array("discount"=>1));
                      break;
                } 
                $cr=new CouponRecords;
                $cr->order_id=$orders->order_id;
                $cr->status=0;
                $cr->coupon_id=$coupon->id;
                $cr->operator=$orders->user_id;
                $cr->save();
            }
            $coupon->used_user_id=0;
            $coupon->use_time=null;
            $coupon->status=2;//如果取消则优惠券状态变为锁定
            $coupon->save();
            CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->delete();
            $coupon_order->status=0;
            $coupon_order->val_status=0;
            $coupon_order->save();
            $orders->discount_amount=0;
            $orders->save();
            Orders::calculate($orders->order_id);            
            return $response;
        });
    }

    /**
     * @Author:      kc
     * @DateTime:    2017-02-24 14:42:29
     * @Description: 是否来过店
     * @Param: $user_id 用户id
     * @Param: $shop_id 门店id
     * @Return: Integer
     */
    public static function getToMaintenanceShops($user_id=Null,$shop_id){
        if(is_null($user_id)) {
            return 0;
        }
        return Orders::where('shop_id',$shop_id)
            ->where('user_id',$user_id)
            ->where('place',2)
            ->whereIn('status',array(1117,1217,1317,1417,1018,1219,1419,1420))
            ->count();
    }

    /**
     * @Author:      kc
     * @DateTime:    2017-02-28 10:21:29
     * @Description: 订单列表
     * @Param: $user_id 用户id
     * @Param: $status 状态 1-全部 2-待确认 3-已确认 4-待评价
     * @Param: $page 第几页
     * @Param: $page_size 每页多少个
     * @Param: $real_name 用户名称
     * @Return: Array
     */
    public static function getOrders($user_id,$status,$page,$page_size,$real_name){
        $orders = Orders::with('maintenanceShops')
            ->where('user_id',$user_id)
            //->where('order_type',1)
            ->where(function($query){
                $query->whereNotIn('pay_user_id',Orders::$not_show_pay_user)
                    ->orwhereNull('pay_user_id');
            });
        //洗车单查询
        $wash_order = CarWashOrder::with('maintenanceShops')->where('user_id',$user_id);

        if((int)$status !== 1){
            $orders->whereIn('status',Orders::$order_status[$status]);
            //洗车单查询
            $wash_order->whereIn('status',Orders::$order_status[$status]);
            if((int)$status == 4) {
                $wash_order->whereNotIn('status',array(1417));
            }
        }
        $data = $orders->get()->toArray();
        $wash_data = $wash_order->get()->toArray();//洗车单查询
        $result = array();
        foreach($data as $v){
            $_status = '';
            foreach(Orders::$order_status as $key => $value){
                if(in_array($v['status'],$value)){
                    $_status = $key;
                }
            }
            $order_detection_num = OrderDetection::where('order_id',$v['order_id'])->count();
            if($order_detection_num >= 1){
                $detection = 1;
            }else{
                $detection = 0;
            }
            $order_type = OrderType::where('order_id',$v['order_id'])->get()->toArray();
            $result[]=array(
                'order_id' => $v['order_id'],
                'user_id' => $v['user_id'],
                'name' => $v['name'],
                'is_wash' => $v['order_type'] == 1 ? 0 :1,//是否是洗车单 0-不是 1-是
                'tittle' => $v['tittle'],
                'phone' => $v['phone'],
                'car_no' => $v['car_no'],
                'shop_name' => isset($v['maintenance_shops']['name'])?$v['maintenance_shops']['name']:'',
                'book_time' => $v['book_time'],
                'book_hour' => $v['book_hour'],
                'place' => $v['place'],
                'detection' => $detection,
                'status' => $_status,
                'status_name' => Orders::$status[$v['status']],
                'is_call' => $v['is_call'],
                'order_type_arr' => $order_type,
                'created_at' => $v['created_at'],
            );
        }
        //洗车单数据处理
        foreach($wash_data as $v){
            $_status = '';
            foreach(Orders::$order_status as $key => $value){
                if(in_array($v['status'],$value)){
                    if($v['status'] == 1417){
                        $_status = 5;
                    }else{
                        $_status = $key;
                    }
                }
            }

            $order_detection_num = OrderDetection::where('order_id',$v['order_id'])->count();
            if($order_detection_num >= 1){
                $detection = 1;
            }else{
                $detection = 0;
            }
            $data=array(
                'order_id' => $v['order_id'],
                'user_id' => $v['user_id'],
                'name' => $real_name,
                'is_wash' => 1,//是否是洗车单 0-不是 1-是
                'phone' => $v['phone'],
                'car_no' => $v['car_no'],
                'shop_name' => isset($v['maintenance_shops']['name'])?$v['maintenance_shops']['name']:'',
                'book_time' => date('Y-m-d',strtotime($v['begin_time'])),
                'book_hour' => date('H:i:s',strtotime($v['end_time'])),
                'place' => "",
                'detection' => $detection,
                'status' => $_status,
                'status_name' => Orders::$status[$v['status']],
                'order_type_arr' => [],
                'created_at' => $v['created_at'],
            );
            array_push($result,$data);
        }
      $sorts = array(
            'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field'     => 'created_at', //排序字段
        );
        if(!empty($result)){
            $arrSort = array();
            foreach($result AS $uniqid => $row){
                foreach($row AS $key=>$value){
                    $arrSort[$key][$uniqid] = $value;
                }
            }
            if($sorts['direction']){
                array_multisort($arrSort[$sorts['field']], constant($sorts['direction']), $result);
            }
        }
        $result = array_slice($result, ($page-1)*$page_size, $page_size);
        return $result;
    }

    /**
     * @Author:      kc
     * @DateTime:    2017-02-28 14:24:29
     * @Description: 订单详情
     * @Param: $user_id 用户id
     * @Param: $order_id 订单Id
     * @Param: $is_wash 是否是洗车单 0-不是 1-是
     * @Return: Array
     */
    public static function getOrderDetails($user_id,$order_id,$is_wash){
        $data = array();
        if($is_wash == 1){
            $wash_order = CarWashOrder::with('maintenanceShops')->where('user_id',$user_id)->where('order_id',$order_id)->first();
            if(!empty($wash_order)) {
                //查询使用的优惠券信息
                $coupon_order_info = DB::table('coupon_order_info')
                    ->leftjoin('coupon_base_info', 'coupon_order_info.coupon_base_info_id', '=', 'coupon_base_info.id')
                    ->where('coupon_order_info.order_id', $order_id)
                    ->where('coupon_order_info.status', 1)
                    ->orderBy('coupon_order_info.id', 'desc')
                    ->first();
                $_status = '';
                foreach (Orders::$order_status as $key => $value) {
                    if (in_array($wash_order->status, $value)) {
                        if ($wash_order->status == 1417) {
                            $_status = 5;
                        } else {
                            $_status = $key;
                        }
                    }
                }
                $order_detection_num = OrderDetection::where('order_id', $wash_order->order_id)->count();
                if ($order_detection_num >= 1) {
                    $detection = 1;
                } else {
                    $detection = 0;
                }
                //是否余额支付的
                $order_pay_record = CarWashOrderPayRecord::where("order_id", $order_id)->where('status',1)->get();
                if (empty($order_pay_record)) {
                    $balance = 0;
                } else {
                    $balance = 0;
                    foreach ($order_pay_record as $v) {
                        if ($v->pay_type == 8) {
                            $balance += $v->amount;
                        }
                    }
                }
                $wash_product = Config::get('config.wash_product');
                $data = array(
                    'order_id' => $wash_order->order_id,
                    'name' => Users::where('id',$user_id)->pluck('real_name'),
                    'phone' => $wash_order->phone,
                    'car_no' => $wash_order->car_no,
                    'shop_name' => isset($wash_order->maintenanceShops->name) ? $wash_order->maintenanceShops->name : '',
                    'address' => "",
                    'book_time' => $wash_order->begin_time,
                    'book_hour' => $wash_order->end_time,
                    'tittle' => "",
                    'amount' => bcdiv($wash_order->amount, 100, 2),
                    'discount_amount' => bcdiv($wash_order->dis_amount, 100, 2),
                    'payable_amount' => bcdiv(bcsub($wash_order->pay_amount, $balance), 100, 2),
                    'balance' => bcdiv($balance, 100, 2),
                    'created_at' => $wash_order->created_at . '',
                    'pay_time' => $wash_order->pay_time . '',
                    'place' => 2,
                    'detection' => $detection,
                    'status' => $_status,
                    'mileage' => 0,
                    'is_call' => "",
                    'order_product_details' => (object)array(),
                    'coupon_info' => $coupon_order_info,
                    'order_type_arr' => [],
                    'wash_type' => $wash_product[$wash_order->producd_id],
                    'is_wash' => 1,
                    'status_value' =>Orders::$status[$wash_order->status],
                );
            }
        }else{
            $orders = Orders::with('maintenanceShops')->where('user_id',$user_id)->where('order_id',$order_id)->first();
            if(!empty($orders)){
                $order_product = OrderProduct::getOrderProductMs($order_id);
                //查询使用的优惠券信息
                $coupon_order_info = DB::table('coupon_order_info')
                    ->leftjoin('coupon_base_info','coupon_order_info.coupon_base_info_id','=','coupon_base_info.id')
                    ->where('coupon_order_info.order_id',$order_id)
                    ->where('coupon_order_info.status',1)
                    ->orderBy('coupon_order_info.id','desc')
                    ->first();
                $_status = '';
                foreach(Orders::$order_status as $key => $value){
                    if(in_array($orders->status,$value)){
                        $_status = $key;
                    }
                }
                $order_detection_num = OrderDetection::where('order_id',$orders->order_id)->count();
                if($order_detection_num >= 1){
                    $detection = 1;
                }else{
                    $detection = 0;
                }
                //订单服务类型
                $order_type = OrderType::where('order_id',$orders->order_id)->get();
                //是否余额支付的
                $order_pay_record = OrderPayRecord::where("order_id",$order_id)->where('status',1)->get();
                if(empty($order_pay_record)){
                    $balance = 0;
                }else{
                    $balance = 0;
                    foreach($order_pay_record as $v){
                        if($v->pay_type == 8){
                            $balance += $v->amount;
                        }
                    }
                }
                $data = array(
                    'order_id' => $orders->order_id,
                    'name' => $orders->name,
                    'phone' => $orders->phone,
                    'car_no' => $orders->car_no,
                    'shop_name' => isset($orders->maintenanceShops->name)?$orders->maintenanceShops->name:'',
                    'address' => $orders->address,
                    'book_time' => $orders->book_time,
                    'book_hour' => $orders->book_hour,
                    'tittle' => $orders->tittle,
                    'amount' => bcdiv($orders->amount,100,2),
                    'discount_amount' => bcdiv($orders->discount_amount,100,2),
                    'payable_amount' => bcdiv(bcsub($orders->payable_amount,$balance),100,2),
                    'balance_amount' => bcdiv($orders->balance_amount,100,2),
                    'balance' => bcdiv($balance,100,2),
                    'created_at' => $orders->created_at.'',
                    'pay_time' => $orders->pay_time.'',
                    'place' => $orders->place,
                    'detection' => $detection,
                    'status' => $_status,
                    'mileage' => $orders->mileage,
                    'is_call' => $orders->is_call,
                    'order_product_details' => $order_product,
                    'coupon_info' => $coupon_order_info,
                    'order_type_arr' => $order_type,
                    'is_wash' => 0,
                    'status_value' =>Orders::$status[$orders->status],
                );
            }
        }
        return $data;
    }

    /**
     * @Author:      dx
     * @DateTime:    2017-3-10 14:17:45
     * @Description: 判断重复下单
     */
    public static function createOrderCheck($car_no,$shop_id){
        $count=Orders::where('car_no',$car_no)->where('shop_id',$shop_id)->whereIn('status',array(1412,1215,1216,1416))->where('order_type',1)->count();
        if($count > 0){
            return true;
        }
        return false;
    }

    /**
     * @Author:      dx
     * @DateTime:    2017-07-07 15:17:45
     * @Description: 下单状态通知
     */
    public static function notifyUserOrderStatus($user_id,$order_id,$title="",$description=""){
        $u_meng_bind = UmengPushBind::where('field_name','user_id')->where('field_value',$user_id)->first();
        if(!$u_meng_bind) return false;

        $order = Orders::find($order_id);
        if(!$order) return false;
        //填充内容
        $data = array(
            'title' => $title,
            'description' => $description,
            'order_id' => $order_id,
            'type' => 1,
            'field_name' => 'user_id',
            'field_value' => $user_id,
        );

        if($u_meng_bind->device_type == 1){ //安卓
            Orders::pushAndroid($u_meng_bind->device_token,$data);
        }else if ($u_meng_bind->device_type = 2){ //iOS
            Orders::pushIOS($u_meng_bind->device_token,$data);
        }
        return true;
    }

    public static function pushAndroid ($device_token,$data = array()){
        ob_start();
        $u_push = new UmengPush(Config::get('u_meng_push.u_Android_AppKey'), Config::get('u_meng_push.u_Android_App_Master_Secret'));

        $log = new UmengPushLog;
        $log->field_name = isset($data['field_name'])?$data['field_name']:"";
        $log->field_value = isset($data['field_value'])?$data['field_value']:"";
        $log->order_id = isset($data['order_id'])?$data['order_id']:"";
        $log->content = isset($data['description'])?$data['description']:"";
        $log->title = isset($data['title'])?$data['title']:"";
        $log->type = isset($data['type'])?$data['type']:1;
        $log->status = UmengPushLog::STATUS_NEW;
        $log->pushed_at = Common::currentTimeString();
        $log->save();
//        $message = array(
//            "title" => $data['title']?$data['title']:"android",
//            "description" => $data['description']?$data['description']:"",
//        );
        try{
            $ret = $u_push->sendAndroidUnicast($device_token,$data);
            $res = json_decode($ret,true);
            if($res['ret'] == "SUCCESS"){
                $r_log = UmengPushLog::find($log->id);
                if($r_log){
                    $r_log->received_at = Common::currentTimeString();
                    $r_log->status = UmengPushLog::STATUS_RECEIVED;
                    $r_log->msg_id = $res['data']['msg_id'];
                    $r_log->save();
                }
                return true;
            }
        }catch (Exception $e) {
            return true;
        }
        ob_end_clean();
        return $ret;
    }

    public static function pushIOS ($device_token,$data = array()){
        ob_start();
        $u_push = new UmengPush(Config::get('u_meng_push.u_Ios_AppKey'), Config::get('u_meng_push.u_Ios_App_Master_Secret'));

        $log = new UmengPushLog;
        $log->field_name = isset($data['field_name'])?$data['field_name']:"";
        $log->field_value = isset($data['field_value'])?$data['field_value']:"";
        $log->order_id = isset($data['order_id'])?$data['order_id']:"";
        $log->content = isset($data['description'])?$data['description']:"";
        $log->title = isset($data['title'])?$data['title']:"";
        $log->type = isset($data['type'])?$data['type']:1;
        $log->status = UmengPushLog::STATUS_NEW;
        $log->pushed_at = Common::currentTimeString();
        $log->save();

        try{
            $ret = $u_push->sendIOSUnicast($device_token,$data);
            $res = json_decode($ret,true);
            if($res['ret'] == "SUCCESS"){
                $r_log = UmengPushLog::find($log->id);
                if($r_log){
                    $r_log->received_at = Common::currentTimeString();
                    $r_log->status = UmengPushLog::STATUS_RECEIVED;
                    $r_log->msg_id = $res['data']['msg_id'];
                    $r_log->save();
                }
                return true;
            }
        }catch (Exception $e) {
            return true;
        }
        ob_end_clean();
        return $ret;
    }

    /**
     * @Author:      dx
     * @DateTime:    2017-07-12 14:17:45
     * @Description: 系统其它信息下发通知
     */
    public static function notifyMsg($user_id,$type,$title="",$description=""){
        $u_meng_bind = UmengPushBind::where('field_name','user_id')->where('field_value',$user_id)->first();
        if(!$u_meng_bind) return false;

        //填充内容
        $data = array(
            'title' => $title,
            'description' => $description,
            'type' => $type,
            'field_name' => 'user_id',
            'field_value' => $user_id,
        );

        if($u_meng_bind->device_type == 1){ //安卓
            Orders::pushAndroid($u_meng_bind->device_token,$data);
        }else if ($u_meng_bind->device_type = 2){ //iOS
            Orders::pushIOS($u_meng_bind->device_token,$data);
        }
        return true;
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-08-16 15:17:45
     * @Description: 套餐卡信息下发通知
     */
    public static function cardnotifyMsg($user_id,$order_id,$type,$title="",$description=""){
        $u_meng_bind = UmengPushBind::where('field_name','user_id')->where('field_value',$user_id)->first();
        if(!$u_meng_bind) return false;

        //填充内容
        $data = array(
            'title' => $title,
            'description' => $description,
            'order_id' => $order_id,
            'type' => $type,
            'field_name' => 'user_id',
            'field_value' => $user_id,
        );

        if($u_meng_bind->device_type == 1){ //安卓
            Orders::pushAndroid($u_meng_bind->device_token,$data);
        }else if ($u_meng_bind->device_type = 2){ //iOS
            Orders::pushIOS($u_meng_bind->device_token,$data);
        }
        return true;
    }



    /**
     * @Author:      sqq
     * @DateTime:    2018-07-31 10:21:29
     * @Description: 订单列表  api3.0
     * @Param: $user_id 用户id
     * @Param: $status 状态 1-全部 2-待确认 3-已确认--待服务 4-已确认--服务中 5-已完成--待评价 6-已完成--已评价 7-已取消 8-已终止
     * @Param: $page 第几页
     * @Param: $page_size 每页多少个
     * @Param: $real_name 用户名称
     * @Return: Array
     */
    public static function OrderList($user_id,$status,$page,$page_size,$real_name,$is_wash){
        $orders = Orders::with('maintenanceShops')
            ->where('user_id',$user_id);
            if($status == 5){
                $orders = $orders->where('order_type',1);
            }
            //
            $orders = $orders->where(function($query){
                $query->whereNotIn('pay_user_id',Orders::$not_show_pay_user)
                    ->orwhereNull('pay_user_id');
            });
        //洗车单查询
        $wash_order = CarWashOrder::with('maintenanceShops')->where('user_id',$user_id);

        if((int)$status !== 1){ //1-全部 2-待确认 3-已确认--待服务 4-已确认--服务中 5-已完成--待评价 6-已完成--已评价 7-已取消 8-已终止
            $orders->whereIn('status',Orders::$order_status_wechat3[$status]);
            //洗车单查询
            $wash_order->whereIn('status',Orders::$order_status_wechat3[$status]);
            if((int)$status == 5) {
                //洗车单不能评价
                $wash_order->whereNotIn('status',array(1417));

                //零售单不能评价
                if($is_wash == 2){
                    $orders->whereNotIn('status',array(1417));
                }
            }
        }
        $data = $orders->get()->toArray();
        $wash_data = $wash_order->get()->toArray();//洗车单查询
        $zhibo = array('code' => 1022, 'msg' => '订单未在服务中。');
        $result = array();
        foreach($data as $v){
            $_status = '';
            foreach(Orders::$order_status_wechat3 as $key => $value){
                if(in_array($v['status'],$value)){
                    $_status = $key;
                }
            }
            $order_detection_num = OrderDetection::where('order_id',$v['order_id'])->count();
            if($order_detection_num >= 1){
                $detection = 1;
            }else{
                $detection = 0;
            }
            $order_type = OrderType::where('order_id',$v['order_id'])->get()->toArray();
            $result[]=array(
                'order_id' => $v['order_id'],
                'user_id' => $v['user_id'],
                'name' => $v['name'],
                'is_wash' => $v['order_type'] == 1 ? 0 :2,//是否是洗车单 0-不是 1-是  0-服务单 2-零售单
                'zhibo' => $zhibo,
                'tittle' => $v['tittle'],
                'phone' => $v['phone'],
                'car_no' => $v['car_no'],
                'shop_name' => isset($v['maintenance_shops']['name'])?$v['maintenance_shops']['name']:'',
                'book_time' => $v['book_time'],
                'book_hour' => $v['book_hour'],
                'place' => $v['place'],
                'detection' => $detection,
                'status' => $_status,
                'status_name' => Orders::$status[$v['status']],
                'real_status' => $v['status'],
                'is_call' => $v['is_call'],
                'order_type_arr' => $order_type,
                'created_at' => $v['created_at'],
                'order_source' => $v['order_source'],
            );
        }
        //洗车单数据处理
        foreach($wash_data as $v){
            $_status = '';
            foreach(Orders::$order_status_wechat3 as $key => $value){
                if(in_array($v['status'],$value)){
                    if($v['status'] == 1417){
                        $_status = 5;
                    }else{
                        $_status = $key;
                    }
                }
            }

//            $order_detection_num = OrderDetection::where('order_id',$v['order_id'])->count();
//            if($order_detection_num >= 1){
//                $detection = 1;
//            }else{
//                $detection = 0;
//            }

            $detection = 0;
            $data=array(
                'order_id' => $v['order_id'],
                'user_id' => $v['user_id'],
                'name' => $real_name,
                'is_wash' => 1,//是否是洗车单 0-不是 1-是
                //'zhibo' => LiveAccessToken::LiveBroadcast($v['user_id'],$v['order_id']),
                'zhibo' => $zhibo,
                'phone' => $v['phone'],
                'car_no' => $v['car_no'],
                'shop_name' => isset($v['maintenance_shops']['name'])?$v['maintenance_shops']['name']:'',
                'book_time' => date('Y-m-d',strtotime($v['begin_time'])),
                'book_hour' => date('H:i:s',strtotime($v['end_time'])),
                'place' => "",
                'detection' => $detection,
                'status' => $_status,
                'status_name' => Orders::$status[$v['status']],
                'real_status' => $v['status'],
                'order_type_arr' => [],
                'created_at' => $v['created_at'],
                'order_source' => 14,
            );
            array_push($result,$data);
        }
        $sorts = array(
            'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field'     => 'created_at', //排序字段
        );

        if(!empty($result)){
            $arrSort = array();
            foreach($result AS $uniqid => $row){
                foreach($row AS $key=>$value){
                    if($is_wash != $row['is_wash'] && $is_wash != -1){
                        unset($result[$uniqid]);
                    }else{
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
            }
            if($sorts['direction'] && $arrSort){
                array_multisort($arrSort[$sorts['field']], constant($sorts['direction']), $result);
            }
        }

        $result = array_slice($result, ($page-1)*$page_size, $page_size);
        if($result){
            foreach($result as $_key => $_val){
                if($_val['is_wash'] == 0){
                    if(in_array($_val['real_status'],Orders::$order_status_wechat3[4])){
                        //$result[$_key]['zhibo'] = LiveAccessToken::LiveBroadcast($_val['user_id'],$_val['order_id']);
                        $station = $station = MaintenanceStationCarStatus::where('order_id',$_val['order_id'])->first();
                        if(!is_null($station)){
                            $result[$_key]['zhibo'] = array('code' => 200, 'msg' => '操作成功');
                        }else{
                            $result[$_key]['zhibo'] = array('code' => 1023, 'msg' => '订单未在工位上。');
                        }
                    }
                }
            }
        }
        return $result;
    }



    /**
     * @Author:      sqq
     * @DateTime:    2018-08-01 11:15:29
     * @Description: api3.0 订单详情
     * @Param: $user_id 用户id
     * @Param: $order_id 订单Id
     * @Param: $is_wash 是否是洗车单 0-不是 1-是 0-服务单 2-零售单
     * @Return: Array
     */
    public static function OrderDetails($user_id,$order_id,$is_wash){
        $data = array();
        if($is_wash == 1){
            $wash_order = CarWashOrder::with('maintenanceShops')->where('user_id',$user_id)->where('order_id',$order_id)->first();
            if(!empty($wash_order)) {
                //查询使用的优惠券信息
                $coupon_order_info = DB::table('coupon_order_info')
                    ->leftjoin('coupon_base_info', 'coupon_order_info.coupon_base_info_id', '=', 'coupon_base_info.id')
                    ->where('coupon_order_info.order_id', $order_id)
                    ->where('coupon_order_info.status', 1)
                    ->orderBy('coupon_order_info.id', 'desc')
                    ->first();
                $_status = '';
                foreach (Orders::$order_status_wechat3 as $key => $value) {
                    if (in_array($wash_order->status, $value)) {
                        if ($wash_order->status == 1417) {
                            $_status = 5;
                        } else {
                            $_status = $key;
                        }
                    }
                }
                $order_detection_num = OrderDetection::where('order_id', $wash_order->order_id)->count();
                if ($order_detection_num >= 1) {
                    $detection = 1;
                } else {
                    $detection = 0;
                }
                //是否余额支付的
                $order_pay_record = CarWashOrderPayRecord::where("order_id", $order_id)->where('status',1)->get();
                if (empty($order_pay_record)) {
                    $balance = 0;
                } else {
                    $balance = 0;
                    foreach ($order_pay_record as $v) {
                        if ($v->pay_type == 8) {
                            $balance += $v->amount;
                        }
                    }
                }
                $wash_product = Config::get('config.wash_product');
                $data = array(
                    'order_id' => $wash_order->order_id,
                    'name' => Users::where('id',$user_id)->pluck('real_name'),
                    'phone' => $wash_order->phone,
                    'car_no' => $wash_order->car_no,
                    'shop_name' => isset($wash_order->maintenanceShops->name) ? $wash_order->maintenanceShops->name : '',
                    'shop_tel' => isset($wash_order->maintenanceShops->tel_phone)?$wash_order->maintenanceShops->tel_phone:'',
                    'address' => "",
                    'book_time' => $wash_order->begin_time,
                    'book_hour' => $wash_order->end_time,
                    'tittle' => "",
                    'amount' => bcdiv($wash_order->amount, 100, 2),
                    'discount_amount' => bcdiv($wash_order->dis_amount, 100, 2),
                    //'payable_amount' => bcdiv(bcsub($wash_order->pay_amount, $balance), 100, 2),
                    'payable_amount' => bcdiv($wash_order->pay_amount, 100, 2),
                    'balance' => bcdiv($balance, 100, 2),
                    'created_at' => $wash_order->created_at . '',
                    'pay_time' => $wash_order->pay_time . '',
                    'place' => 2,
                    'detection' => $detection,
                    'status' => $_status,
                    'mileage' => 0,
                    'is_call' => "",
                    'order_product_details' => (object)array(),
                    'coupon_info' => $coupon_order_info,
                    'order_type_arr' => [],
                    'wash_type' => $wash_product[$wash_order->producd_id],
                    'is_wash' => 1,
                    'status_value' =>Orders::$status[$wash_order->status],
                    'zhibo' => LiveAccessToken::LiveBroadcast($user_id,$wash_order->order_id),
                    'reception_id' => $wash_order->reception_id,
                    'reception_name' => $wash_order->reception_name,
                    'estimated_completion_time' => $wash_order->estimated_completion_time,
                    'book_hours' => '',
                    'real_status' => $wash_order->status,
                    'order_source' => 14,
                    'discount' => $wash_order->dis_amount
                );
            }
        }else{
            $orders = Orders::with('maintenanceShops')->where('user_id',$user_id)->where('order_id',$order_id)->first();
            if(!empty($orders)){
                //$order_product = OrderProduct::getOrderProductMs($order_id);
                $order_product = OrderProduct::getOrderProductById($order_id);
                //查询使用的优惠券信息
                $coupon_order_info = DB::table('coupon_order_info')
                    ->leftjoin('coupon_base_info','coupon_order_info.coupon_base_info_id','=','coupon_base_info.id')
                    ->where('coupon_order_info.order_id',$order_id)
                    ->where('coupon_order_info.status',1)
                    ->orderBy('coupon_order_info.id','desc')
                    ->first();
                if(!empty($coupon_order_info)){
                    $coupon_order_info->amount = bcdiv($coupon_order_info->amount,100,2);
                }
                $_status = '';
                foreach(Orders::$order_status_wechat3 as $key => $value){
                    if(in_array($orders->status,$value)){
                        $_status = $key;
                    }
                }
                $order_detection_num = OrderDetection::where('order_id',$orders->order_id)->count();
                if($order_detection_num >= 1){
                    $detection = 1;
                }else{
                    $detection = 0;
                }
                //订单服务类型
                $order_type = OrderType::where('order_id',$orders->order_id)->get();
                //是否余额支付的
                $order_pay_record = OrderPayRecord::where("order_id",$order_id)->where('status',1)->get();
                if(empty($order_pay_record)){
                    $balance = 0;
                }else{
                    $balance = 0;
                    foreach($order_pay_record as $v){
                        if($v->pay_type == 8){
                            $balance += $v->amount;
                        }
                    }
                }
                $data = array(
                    'order_id' => $orders->order_id,
                    'name' => $orders->name,
                    'phone' => $orders->phone,
                    'car_no' => $orders->car_no,
                    'shop_name' => isset($orders->maintenanceShops->name)?$orders->maintenanceShops->name:'',
                    'shop_tel' => isset($orders->maintenanceShops->tel_phone)?$orders->maintenanceShops->tel_phone:'',
                    'address' => $orders->address,
                    'book_time' => $orders->book_time,
                    'book_hour' => $orders->book_hour,
                    'tittle' => $orders->tittle,
                    'amount' => bcdiv($orders->amount,100,2),
                    'discount_amount' => bcdiv($orders->discount_amount,100,2),
                    'payable_amount' => bcdiv(bcsub($orders->payable_amount,$balance),100,2),
                    'balance_amount' => bcdiv($orders->balance_amount,100,2),
                    'balance' => bcdiv($balance,100,2),
                    'created_at' => $orders->created_at.'',
                    'pay_time' => $orders->pay_time.'',
                    'place' => $orders->place,
                    'detection' => $detection,
                    'status' => $_status,
                    'mileage' => $orders->mileage,
                    'is_call' => $orders->is_call,
                    'order_product_details' => $order_product,
                    'coupon_info' => $coupon_order_info,
                    'order_type_arr' => $order_type,
                    'is_wash' => 0,
                    'status_value' =>Orders::$status[$orders->status],
                    'zhibo' => LiveAccessToken::LiveBroadcast($user_id,$orders->order_id),
                    'reception_id' => $orders->reception_id,
                    'reception_name' => $orders->reception_name,
                    'estimated_completion_time' => $orders->estimated_completion_time,
                    'real_status' => $orders->status,
                    'order_source' => $orders->order_source,
                    'discount' => bcdiv($orders->discount,100,2)
                );
                if(!empty($data) && !empty($data['book_hour'])){
                    $data['book_hours'] = explode('-',$data['book_hour'])[0];
                    $data['book_time'] = $data['book_time'].' '.$data['book_hours'];
                }
            }
        }

        if(!empty($data)){
            $data['service'] = Shopping::with('Ahp_service')->where('order_id',$data['order_id'])->first();
            if(!empty($data['service'])){
                $data['service']->price = bcdiv($data['service']->price,100,2);
                $data['service']->count_amount = bcdiv($data['service']->count_amount,100,2);
            }
        }

        return $data;
    }


    //下单成功记录到消息表
    public static function pushMessage ($data = array()){
        try{
            $log = new NewsLog();
            $log->field_name = isset($data['field_name'])?$data['field_name']:"";
            $log->field_value = isset($data['field_value'])?$data['field_value']:"";
            $log->order_id = isset($data['order_id'])?$data['order_id']:"";
            $log->content = isset($data['description'])?$data['description']:"";
            $log->title = isset($data['title'])?$data['title']:"";
            $log->type = isset($data['type'])?$data['type']:1;
            $log->order_type = $data['order_type'];
            $log->status = NewsLog::STATUS_NEW;
            $log->pushed_at = Common::currentTimeString();
            $log->save();
            $response = array('code' => 10000, 'msg' => '消息保存成功');
            Log::info("info", array("system" => "api3.0" ,"event" => "pushMessage", 'input' =>Input::all() ,"output" => $response));
            return $response;
        }catch (Exception $e) {
            $response = array('code' => 10000, 'msg' => '消息保存失败');
            Log::info("info", array("system" => "api3.0" ,"event" => "pushMessage", 'input' =>Input::all() ,"output" => $response));
            return $response;
        }
    }

    //查询订单状态
    public static function order_status($order_id){
        $status = Orders::where('order_id',$order_id)->first();
        $order_status = null;
        if(!is_null($status)){
            $order_status = $status->status;
        }
        return $order_status;
    }

    //查询保养里程
    public static function order_mileage($order_id){
        $status = Orders::where('order_id',$order_id)->first();
        $order_mileage = 0;
        if(!is_null($status)){
            $order_mileage = !empty($status->mileage) ? $status->mileage : 0;
        }
        return $order_mileage;
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-10-16 09:52:45
     * @Description: 判断重复下单(微站3.0版本)
     */
    public static function createOrderCheck3($car_no,$shop_id){
        $count=Orders::where('car_no',$car_no)->where('shop_id',$shop_id)->whereIn('status',array(1215,1216,1416,1420))->where('order_type',1)->count();
        if($count > 0){
            return true;
        }
        return false;
    }


}